Web连接测试
在本实验中,只有一个任务:运行网络故障诊断包。当你成功做到了,你需要寻找“实例ID”敲入回车键,运行Web连接测试,并且从一个指定的页面中寻求帮助。
使用http://videotraining.interfacett.com作为测试地址。如果获取的返回信息是“没有发现问题”,这意味着成功地运行了该检查。
# Get-TroubleshootingPack默认已存在,可跳过该步骤PS D:\(Tmp> get-module *trouble* -list目录: C:\Windows\system32\WindowsPowerShell\v1.0\ModulesModuleType Version Name ExportedCommandsManifest 1.0.0.0 TroubleshootingPack {Get-TroubleshootingPack, Invoke-TroubleshootingPack}PS D:\(Tmp> Import-Module TroubleshootingPackCommandType Name Version Source----------- ---- ------- ------Cmdlet Get-TroubleshootingPack 1.0.0.0 TroubleshootingPackCmdlet Invoke-TroubleshootingPack 1.0.0.0 TroubleshootingPack
PS D:\(Tmp> dir C:\windows\diagnostics\system目录: C:\windows\diagnostics\systemMode LastWriteTime Length Name---- ------------- ------ ----d----- 2019/12/7 22:44 Appsd----- 2019/12/7 22:44 Audiod----- 2019/12/7 22:44 BITSd----- 2021/7/11 7:24 Bluetoothd----- 2019/12/7 22:44 Deviced----- 2019/12/7 22:44 DeviceCenterd----- 2019/12/7 22:44 IEBrowseWebd----- 2019/12/7 22:44 IESecurityd----- 2019/12/7 22:44 Keyboardd----- 2019/12/7 22:44 Networkingd----- 2021/10/21 10:19 PCWd----- 2019/12/7 22:44 Powerd----- 2019/12/7 22:44 Printerd----- 2019/12/7 22:44 Searchd----- 2019/12/7 22:44 Speechd----- 2019/12/7 22:44 Videod----- 2019/12/7 22:47 WindowsMediaPlayerConfigurationd----- 2019/12/7 22:47 WindowsMediaPlayerMediaLibraryd----- 2019/12/7 22:47 WindowsMediaPlayerPlayDVDd----- 2019/12/7 22:44 WindowsUpdate
PS D:\(Tmp> $pack=get-troubleshootingpack位于命令管道位置 1 的 cmdlet Get-TroubleshootingPack请为以下参数提供值:Path: C:\windows\diagnostics\system\Networking # 使用Networking诊断工具# 调用诊断PS D:\(Tmp> Invoke-TroubleshootingPack $pack正在启动网络诊断... -1实例 ID请勿指定 MSDT 以外的应用程序。: # 此处直接按回车选择入口点请选择网络诊断的入口点。[1] Web 连接[2] 文件共享[3] 网络适配器[4] Winsock 连接[5] 分组[6] 入站[7] DirectAccess[8] DefaultConnectivity[9] 已保留[?] 帮助[x] 退出:1 # 输入序号1请选择 Windows 应该解决的问题[1] 连接到 Internet 的疑难解答[2] 帮助我连接到特定网页[?] 帮助[x] 退出:2 # 输入序号2输入要访问的网站地址例如,http://www.microsoft.com。: https://www.pluralsight.com/browse/it-ops # 输入测试站点正在查找问题... -1正在查看 Web 连接 中的问题... -1正在收集结果... -1-1正在收集配置详细信息... -1-1未检测到任何问题 # 诊断结果
查看补丁列表
显示已安装的补丁列表,按照补丁描述对结果进行排序,并输出描述、补丁ID、安装日期列,最终将结果保存到HTML文件。
Get-HotFix | Sort Description | Select Description, InstalledOn, InstalledBy, HotFixID |ConvertTo-Html -Title "HotFix Report" | Out-File HotFixReport.htm
获取服务清单
使用括号而不要使用管道输入方法,来获取域中每一台计算机上已经安装的服务清单。
Get-Service -ComputerName (Get-ADComputer dn2d-00088 |Select-Object -ExpandProperty Name)
格式化输出
以列表形式显示C:\Windows目录中所有的.exe文件的名称、版本信息以及文件大小。PowerShell使用length属性,但你的输出结果应该显示为Size。
dir c:\windows\*.exe | Format-list Name, VersionInfo, @{Name= "Size"; Expression={$_.length}}
过滤和比较
1)显示所有位于C:\Windows\System32下且大于5MB的EXE文件
Dir c:\windows\system32\*.exe | where {$_.length –gt 5MB}
2)使用Get-DnsClientCache命令显示一个从缓存中读取的A和AAAA列表
Get-DnsClientCache -type AAAA, A
3)显示属于安全更新的补丁列表
Get-Hotfix -Description 'Security Update'
4)显示一个管理员安装过的补丁列表,并列出哪些是更新补丁。如果没有任何补丁,请尝试找出由System账户安装的补丁。注意,有些补丁包没有“installed by”这个值。
get-hotfix -Description Update | where {$_.InstalledBy -match "administrator"}# 或get-hotfix -Description Update | where {$_.InstalledBy -match "system"}# 或get-hotfix -Description Update | where {$_.InstalledBy -eq "NTAuthority\System"}
目录共享
创建一个名称为“LABS”的目录,并共享该目录。先不用管NTFS的权限问题,但请确保共享目录的权限设置为“所有人”拥有读/写权限,并且本地管理员拥有完全控制权。由于共享的主要是文件,所以为文档设置共享缓存。最后,展示新建的共享及其权限。
# 创建目录New-item -Path "D:\(Tmp\LABS\" -Type Directory | Out-Null# 创建共享PS C:\Windows\system32> $myShare = New-SmbShare -Name Labs -Path "D:\(Tmp\LABS\"`>> -Description "My Lab Share" -ChangeAccess Everyone `>> -FullAccess administrators -CachingMode Documents# 获取共享权限PS C:\Windows\system32> $myShare | Get-SmbShareAccessName ScopeName AccountName AccessControlType AccessRight---- --------- ----------- ----------------- -----------Labs * BUILTIN\Administrators Allow FullLabs * Everyone Allow ChangePS C:\Windows\system32> $myShare | Get-SmbShareName ScopeName Path Description---- --------- ---- -----------Labs * D:\(Tmp\LABS My Lab Share
远程处理
使用Invoke-Command查询一个或多个远程计算机,从而显示来自注册表键(HKEY_Local_Machine\SOFTWARE\Microsoft\Windows NT\CurrentVersion)的ProductName、EditionID、CurrentVersion这3个属性。
提示:这需要你获得一个项(item)的属性。
invoke-command –scriptblock {get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\' | Select ProductName, EditionID, CurrentVersion} -computername Server01, Server02
Windows管理规范
1)使用什么类可以查看一个网卡的当前IP地址?这个类是否有什么方法可用于释放DHCP租期?
- 可以使用
Win32_NetworkAdapterConfiguration类 
- 运行Get-Wmiobject并通过管道传输给Get-Member,可以看到大量DHCP相关的方法。
- 还可以使用CIM cmdlet发现这些。 ```powershell PS C:> Get-CimClass win32_networkadapterconfiguration | select -ExpandProperty CimClassMethods | where name -Match “dhcp”
Name ReturnType Parameters Qualifiers
EnableDHCP UInt32 {} {Implemented, MappingStrings, ValueMap} RenewDHCPLease UInt32 {} {Implemented, MappingStrings, ValueMap} RenewDHCPLeaseAll UInt32 {} {Implemented, MappingStrings, Static, ValueMap} ReleaseDHCPLease UInt32 {} {Implemented, MappingStrings, ValueMap} ReleaseDHCPLeaseAll UInt32 {} {Implemented, MappingStrings, Static, ValueMap}
2)创建一个显示计算机名称、操作系统版本号、操作系统描述(标题)和BIOS序列号的表格。```powershell# 使用wmi实现PS C:\> gwmi -Class win32_operatingsystem | ft PSComputerName, Version, Caption,>> @{name='SerialNumber'; e={gwmi win32_bios | select -ExpandProperty SerialNumber}} -AutoSizePSComputerName Version Caption SerialNumber-------------- ------- ------- ------------IM20211010 10.0.19042 Microsoft Windows 10 企业版 M9NRCX05M144394# 使用cim实现PS C:\> get-ciminstance win32_operatingsystem | Select BuildNumber, Caption,@{l='Computername'; e={$_.CSName}},@{l='BIOSSerialNumber'; e={(get-ciminstance win32_bios).serialnumber}} | ft -autoBuildNumber Caption Computername BIOSSerialNumber----------- ------- ------------ ----------------19042 Microsoft Windows 10 企业版 IM20211010 M9NRCX05M144394
3)使用WMI查询关于热修复补丁(hotfixes)的列表。
Get-CimInstance -ClassName Win32_QuickFixEngineering
4)显示服务列表,在列表中包含它们的当前状态、启动模式和启动账号信息。
5)使用CIM cmdlet,显示在SecurityCenter2命名空间内,并且以Product作为路径列表一部分的所有可用列。
PS C:\> get-cimclass -namespace root/SecurityCenter2 -ClassName *product | ft -AutoSizeNameSpace:ROOT/SecurityCenter2CimClassName CimClassMethods CimClassProperties------------ --------------- ------------------AntiVirusProduct {} {displayName, instanceGuid, pathTo...AntiSpywareProduct {} {displayName, instanceGuid, pathTo...FirewallProduct {} {displayName, instanceGuid, pathTo...
6)使用CIM cmdlet显示所有反间谍软件和反病毒产品
get-ciminstance -namespace root/SecurityCenter2 -ClassName AntiSpywareProductget-ciminstance -namespace root/SecurityCenter2 -ClassName AntiVirusProduct
多任务后台作业
1)创建一次性的后台作业用于寻找C:驱动器中所有的PowerShell脚本。
Start-Job {dir c:\ -recurse –filter '*.ps1'}
2)你意识到该后台作业在一些服务器上识别所有PowerShell脚本非常有效。该如何在一组远程计算机上运行任务1中相同的命令呢?
Invoke-Command –scriptblock {dir c:\ -recurse –filter *.ps1} –computername (get-content computers.txt) -asjob
3)创建一个后台作业,用于获取系统事件日志中最近的25条错误记录,之后将记录导出为CliXML。并在每周一到周五的早上6点运行。
$Trigger=New-JobTrigger -At "6:00AM" -DaysOfWeek "Monday","Tuesday","Wednesday", "Thursday", "Friday" –Weekly$command={ Get-EventLog -LogName System -Newest 25 -EntryType Error | Export-Clixml c:\work\25SysErr.xml}Register-ScheduledJob -Name "Get 25 System Errors" -ScriptBlock $Command -Trigger $Trigger# 检查被创建的作业Get-ScheduledJob | Select *
使用变量
- 创建一个后台作业,从两台计算机中查询Win32_BIOS信息(如果你只有一台计算机做实验,可以使用两次“localhost”模拟)。
- 当作业运行完毕后,把作业的结果存入一个变量。
- 显示变量的内容。
- 把变量内容导出到一个CliXML文件中。 ```powershell PS C:> invoke-command {get-wmiobject win32_bios} –computername localhost,$env:computername –asjob
PS C:>$results=Receive-Job 4 –keep
PS C:>$results PS C:>$results | export-clixml bios.xml
<a name="QxZrp"></a>## 输入输出请使用单行命令完成,且不要使用变量:提示用户输入姓名,并且仅当长度大于5时才显示该姓名。```powershellRead-Host "Pls Enter your name" | where {$_.Length -gt 5}
编写带有参数的脚本
获取所有可用空间,小于指定百分比的本地驱动器(默认为本机小于10%的磁盘可以空间)。
<#.SynopsisGet drives based on percentage free space..DescriptionThis command will get all local drives that have less than the specifiedpercentage of free space available..Parameter ComputernameThe name of the computer to check. The default is localhost..Parameter MinimumPercentFreeThe minimum percent free diskspace. This is the threshhold. The default valueis 10. Enter a number between 1 and 100..ExamplePS C:\Get-Disk -minimum 20Find all disks on the local computer with less than 20% free space..ExamplePS C:\>Get-Disk -comp SERVER02 -minimum 25Find all local disks on SERVER02 with less than 25% free space.#>Param ($ComputerName='localhost',$MinimumPercentFree=10)# Convert minimum percent free$minpercent=$MinimumPercentFree/100Get-WmiObject -class Win32_LogicalDisk -ComputerName $computername -filter "drivetype=3" |Where {$_.FreeSpace / $_.Size -lt $minpercent} |# Where {$_.FreeSpace / $_.Size -lt .1} | # 此处 .1表示10%Select -Property DeviceID,FreeSpace,Size
优化参数脚本
需要将-ComputerName参数变为强制参数,并给它一个名称为hostname的别名。并且使得脚本可以在运行命令之前和之后,显示详细输出。
<#.SYNOPSISGet physical network adapters..DESCRIPTION通过Win32_NetworkAdapter,获取全部的物理网卡信息。.PARAMETER computernameThe name of the computer to check..EXAMPLEGet-PhysicalAdapter -computername SERVER-R2#>[CmdletBinding()]Param([Parameter(Mandatory=$True, HelpMessage="Enter a computer name to query")][Alias('hostname')][string]$computername)Write-Verbose "Getting physical network adapters from $computername"Get-CimInstance Win32_NetworkAdapter -ComputerName $computer |Where-Object {$_.PhysicalAdapter} |Select-Object MACAddress, AdapterType, DeviceID, Name, SpeedWrite-Verbose "Script Finished!"
高级远程控制
在本地计算机创建一个名称为TestPoint的端点。将端点配置为仅自动载入SmbShare组件,但该组件只有Get-SmbShare命令可见。同时要确保类似Exit-PSSession的关键Cmdlet可见,但不允许使用其他核心PowerShell Cmdlet。
通过Enter-PSSession(指定localhost作为计算机名称,TestPoint作为配置名称)连接到该端口,对该端口进行测试。当连接成功后,运行Get-Command,从而确保只有少数配置为可见的命令可以被发现。
# 创建会话配置文件PS C:\> New-PSSessionConfigurationFile -Path 'C:\itsTestEndpoint.pssc' -ModulesToImport SmbShare -SessionType RestrictedRemoteServer -CompanyName "IM30" -Author "Rick Guo" -Description "restricted SMBShare endpoint" -PowerShellVersion '5.0'# 注册配置# PS C:\> Register-PSSessionConfiguration -Path "C:\itsTestEndpoint.pssc" -RunAsCredential im30\rick -ShowSecurityDescriptorUI -Name TestPointPS C:\> Register-PSSessionConfiguration -Path "C:\itsTestEndpoint.pssc" -Name TestPoint# 连接端点PS C:\> Enter-PSSession -ComputerName localhost -ConfigurationName TestPoint
使用正则
- 获取活动目录中所有名称包含两位数字的文件。
- 获得计算机中所有来自微软的进程,并显示进程ID、名称以及公司名称。提示:通过管道将Get-Process传递给Get-Member,从而显示属性名称。
- 在Windows Update日志中,该日志通常位于C:\Windows,你只希望显示代理开始安装文件的日志行。你或许需要在记事本中打开日志文件,从而找出你需要选择的字符串。
- 使用Get-DNSClientCache这个cmdlet显示列表,该列表仅显示Data属性为IPV4地址的条目。
# 1.dir c:\windows | where {$_.name -match "\d{2}"}# 2.get-process | where {$_.company -match "^Microsoft"} | Select Name, ID, Company# 3.get-content C:\Windows\WindowsUpdate.log | Select-string "Start[\w+\W+]+Agent: Installing Updates"# 4.可以通过匹配以1~3位数字后跟着一个句号为开头的模式获得结果,如下:get-dnsclientcache | where { $_.data -match "^\d{1,3}\."}# 或者可以匹配整个IPv4地址字符串:get-dnsclientcache | where{ $_.data -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"}
