Web连接测试

在本实验中,只有一个任务:运行网络故障诊断包。当你成功做到了,你需要寻找“实例ID”敲入回车键,运行Web连接测试,并且从一个指定的页面中寻求帮助。
使用http://videotraining.interfacett.com作为测试地址。如果获取的返回信息是“没有发现问题”,这意味着成功地运行了该检查。

  1. # Get-TroubleshootingPack默认已存在,可跳过该步骤
  2. PS D:\(Tmp> get-module *trouble* -list
  3. 目录: C:\Windows\system32\WindowsPowerShell\v1.0\Modules
  4. ModuleType Version Name ExportedCommands
  5. Manifest 1.0.0.0 TroubleshootingPack {Get-TroubleshootingPack, Invoke-TroubleshootingPack}
  6. PS D:\(Tmp> Import-Module TroubleshootingPack
  7. CommandType Name Version Source
  8. ----------- ---- ------- ------
  9. Cmdlet Get-TroubleshootingPack 1.0.0.0 TroubleshootingPack
  10. Cmdlet Invoke-TroubleshootingPack 1.0.0.0 TroubleshootingPack
  1. PS D:\(Tmp> dir C:\windows\diagnostics\system
  2. 目录: C:\windows\diagnostics\system
  3. Mode LastWriteTime Length Name
  4. ---- ------------- ------ ----
  5. d----- 2019/12/7 22:44 Apps
  6. d----- 2019/12/7 22:44 Audio
  7. d----- 2019/12/7 22:44 BITS
  8. d----- 2021/7/11 7:24 Bluetooth
  9. d----- 2019/12/7 22:44 Device
  10. d----- 2019/12/7 22:44 DeviceCenter
  11. d----- 2019/12/7 22:44 IEBrowseWeb
  12. d----- 2019/12/7 22:44 IESecurity
  13. d----- 2019/12/7 22:44 Keyboard
  14. d----- 2019/12/7 22:44 Networking
  15. d----- 2021/10/21 10:19 PCW
  16. d----- 2019/12/7 22:44 Power
  17. d----- 2019/12/7 22:44 Printer
  18. d----- 2019/12/7 22:44 Search
  19. d----- 2019/12/7 22:44 Speech
  20. d----- 2019/12/7 22:44 Video
  21. d----- 2019/12/7 22:47 WindowsMediaPlayerConfiguration
  22. d----- 2019/12/7 22:47 WindowsMediaPlayerMediaLibrary
  23. d----- 2019/12/7 22:47 WindowsMediaPlayerPlayDVD
  24. d----- 2019/12/7 22:44 WindowsUpdate
  1. PS D:\(Tmp> $pack=get-troubleshootingpack
  2. 位于命令管道位置 1 cmdlet Get-TroubleshootingPack
  3. 请为以下参数提供值:
  4. Path: C:\windows\diagnostics\system\Networking # 使用Networking诊断工具
  5. # 调用诊断
  6. PS D:\(Tmp> Invoke-TroubleshootingPack $pack
  7. 正在启动网络诊断... -1
  8. 实例 ID
  9. 请勿指定 MSDT 以外的应用程序。
  10. : # 此处直接按回车
  11. 选择入口点
  12. 请选择网络诊断的入口点。
  13. [1] Web 连接
  14. [2] 文件共享
  15. [3] 网络适配器
  16. [4] Winsock 连接
  17. [5] 分组
  18. [6] 入站
  19. [7] DirectAccess
  20. [8] DefaultConnectivity
  21. [9] 已保留
  22. [?] 帮助
  23. [x] 退出
  24. :1 # 输入序号1
  25. 请选择 Windows 应该解决的问题
  26. [1] 连接到 Internet 的疑难解答
  27. [2] 帮助我连接到特定网页
  28. [?] 帮助
  29. [x] 退出
  30. :2 # 输入序号2
  31. 输入要访问的网站地址
  32. 例如,http://www.microsoft.com。
  33. : https://www.pluralsight.com/browse/it-ops # 输入测试站点
  34. 正在查找问题... -1
  35. 正在查看 Web 连接 中的问题... -1
  36. 正在收集结果... -1
  37. -1
  38. 正在收集配置详细信息... -1
  39. -1
  40. 未检测到任何问题 # 诊断结果

查看补丁列表

显示已安装的补丁列表,按照补丁描述对结果进行排序,并输出描述、补丁ID、安装日期列,最终将结果保存到HTML文件。

  1. Get-HotFix | Sort Description | Select Description, InstalledOn, InstalledBy, HotFixID |ConvertTo-Html -Title "HotFix Report" | Out-File HotFixReport.htm

获取服务清单

使用括号而不要使用管道输入方法,来获取域中每一台计算机上已经安装的服务清单。

  1. Get-Service -ComputerName (Get-ADComputer dn2d-00088 |
  2. Select-Object -ExpandProperty Name)

image.png

格式化输出

以列表形式显示C:\Windows目录中所有的.exe文件的名称、版本信息以及文件大小。PowerShell使用length属性,但你的输出结果应该显示为Size。

  1. dir c:\windows\*.exe | Format-list Name, VersionInfo, @{Name= "Size"; Expression={$_.length}}

image.png

过滤和比较

1)显示所有位于C:\Windows\System32下且大于5MB的EXE文件

  1. Dir c:\windows\system32\*.exe | where {$_.length gt 5MB}

2)使用Get-DnsClientCache命令显示一个从缓存中读取的A和AAAA列表

  1. Get-DnsClientCache -type AAAA, A

3)显示属于安全更新的补丁列表

  1. Get-Hotfix -Description 'Security Update'

4)显示一个管理员安装过的补丁列表,并列出哪些是更新补丁。如果没有任何补丁,请尝试找出由System账户安装的补丁。注意,有些补丁包没有“installed by”这个值。

  1. get-hotfix -Description Update | where {$_.InstalledBy -match "administrator"}
  2. # 或
  3. get-hotfix -Description Update | where {$_.InstalledBy -match "system"}
  4. # 或
  5. get-hotfix -Description Update | where {$_.InstalledBy -eq "NTAuthority\System"}

目录共享

创建一个名称为“LABS”的目录,并共享该目录。先不用管NTFS的权限问题,但请确保共享目录的权限设置为“所有人”拥有读/写权限,并且本地管理员拥有完全控制权。由于共享的主要是文件,所以为文档设置共享缓存。最后,展示新建的共享及其权限。

  1. # 创建目录
  2. New-item -Path "D:\(Tmp\LABS\" -Type Directory | Out-Null
  3. # 创建共享
  4. PS C:\Windows\system32> $myShare = New-SmbShare -Name Labs -Path "D:\(Tmp\LABS\"`
  5. >> -Description "My Lab Share" -ChangeAccess Everyone `
  6. >> -FullAccess administrators -CachingMode Documents
  7. # 获取共享权限
  8. PS C:\Windows\system32> $myShare | Get-SmbShareAccess
  9. Name ScopeName AccountName AccessControlType AccessRight
  10. ---- --------- ----------- ----------------- -----------
  11. Labs * BUILTIN\Administrators Allow Full
  12. Labs * Everyone Allow Change
  13. PS C:\Windows\system32> $myShare | Get-SmbShare
  14. Name ScopeName Path Description
  15. ---- --------- ---- -----------
  16. Labs * D:\(Tmp\LABS My Lab Share

image.png

远程处理

使用Invoke-Command查询一个或多个远程计算机,从而显示来自注册表键(HKEY_Local_Machine\SOFTWARE\Microsoft\Windows NT\CurrentVersion)的ProductName、EditionID、CurrentVersion这3个属性。
提示:这需要你获得一个项(item)的属性。

  1. invoke-command scriptblock {get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\' | Select ProductName, EditionID, CurrentVersion} -computername Server01, Server02

Windows管理规范

1)使用什么类可以查看一个网卡的当前IP地址?这个类是否有什么方法可用于释放DHCP租期?

  • 可以使用Win32_NetworkAdapterConfiguration
  • image.png
  • 运行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}

  1. 2)创建一个显示计算机名称、操作系统版本号、操作系统描述(标题)和BIOS序列号的表格。
  2. ```powershell
  3. # 使用wmi实现
  4. PS C:\> gwmi -Class win32_operatingsystem | ft PSComputerName, Version, Caption,
  5. >> @{name='SerialNumber'; e={gwmi win32_bios | select -ExpandProperty SerialNumber}} -AutoSize
  6. PSComputerName Version Caption SerialNumber
  7. -------------- ------- ------- ------------
  8. IM20211010 10.0.19042 Microsoft Windows 10 企业版 M9NRCX05M144394
  9. # 使用cim实现
  10. PS C:\> get-ciminstance win32_operatingsystem | Select BuildNumber, Caption,@{l='Computername'; e={$_.CSName}},@{l='BIOSSerialNumber'; e={(get-ciminstance win32_bios).serialnumber}} | ft -auto
  11. BuildNumber Caption Computername BIOSSerialNumber
  12. ----------- ------- ------------ ----------------
  13. 19042 Microsoft Windows 10 企业版 IM20211010 M9NRCX05M144394

3)使用WMI查询关于热修复补丁(hotfixes)的列表。

  1. Get-CimInstance -ClassName Win32_QuickFixEngineering

4)显示服务列表,在列表中包含它们的当前状态、启动模式和启动账号信息。
image.png
5)使用CIM cmdlet,显示在SecurityCenter2命名空间内,并且以Product作为路径列表一部分的所有可用列。

  1. PS C:\> get-cimclass -namespace root/SecurityCenter2 -ClassName *product | ft -AutoSize
  2. NameSpace:ROOT/SecurityCenter2
  3. CimClassName CimClassMethods CimClassProperties
  4. ------------ --------------- ------------------
  5. AntiVirusProduct {} {displayName, instanceGuid, pathTo...
  6. AntiSpywareProduct {} {displayName, instanceGuid, pathTo...
  7. FirewallProduct {} {displayName, instanceGuid, pathTo...

6)使用CIM cmdlet显示所有反间谍软件和反病毒产品

  1. get-ciminstance -namespace root/SecurityCenter2 -ClassName AntiSpywareProduct
  2. get-ciminstance -namespace root/SecurityCenter2 -ClassName AntiVirusProduct

image.png

多任务后台作业

1)创建一次性的后台作业用于寻找C:驱动器中所有的PowerShell脚本。

  1. Start-Job {dir c:\ -recurse filter '*.ps1'}

2)你意识到该后台作业在一些服务器上识别所有PowerShell脚本非常有效。该如何在一组远程计算机上运行任务1中相同的命令呢?

  1. Invoke-Command scriptblock {dir c:\ -recurse filter *.ps1} computername (get-content computers.txt) -asjob

3)创建一个后台作业,用于获取系统事件日志中最近的25条错误记录,之后将记录导出为CliXML。并在每周一到周五的早上6点运行。

  1. $Trigger=New-JobTrigger -At "6:00AM" -DaysOfWeek "Monday","Tuesday","Wednesday", "Thursday", "Friday" Weekly
  2. $command={ Get-EventLog -LogName System -Newest 25 -EntryType Error | Export-Clixml c:\work\25SysErr.xml}
  3. Register-ScheduledJob -Name "Get 25 System Errors" -ScriptBlock $Command -Trigger $Trigger
  4. # 检查被创建的作业
  5. Get-ScheduledJob | Select *

使用变量

  1. 创建一个后台作业,从两台计算机中查询Win32_BIOS信息(如果你只有一台计算机做实验,可以使用两次“localhost”模拟)。
  2. 当作业运行完毕后,把作业的结果存入一个变量。
  3. 显示变量的内容。
  4. 把变量内容导出到一个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

  1. <a name="QxZrp"></a>
  2. ## 输入输出
  3. 请使用单行命令完成,且不要使用变量:提示用户输入姓名,并且仅当长度大于5时才显示该姓名。
  4. ```powershell
  5. Read-Host "Pls Enter your name" | where {$_.Length -gt 5}

image.png

编写带有参数的脚本

获取所有可用空间,小于指定百分比的本地驱动器(默认为本机小于10%的磁盘可以空间)。
image.png

  1. <#
  2. .Synopsis
  3. Get drives based on percentage free space.
  4. .Description
  5. This command will get all local drives that have less than the specified
  6. percentage of free space available.
  7. .Parameter Computername
  8. The name of the computer to check. The default is localhost.
  9. .Parameter MinimumPercentFree
  10. The minimum percent free diskspace. This is the threshhold. The default value
  11. is 10. Enter a number between 1 and 100.
  12. .Example
  13. PS C:\Get-Disk -minimum 20
  14. Find all disks on the local computer with less than 20% free space.
  15. .Example
  16. PS C:\>Get-Disk -comp SERVER02 -minimum 25
  17. Find all local disks on SERVER02 with less than 25% free space.
  18. #>
  19. Param (
  20. $ComputerName='localhost',
  21. $MinimumPercentFree=10
  22. )
  23. # Convert minimum percent free
  24. $minpercent=$MinimumPercentFree/100
  25. Get-WmiObject -class Win32_LogicalDisk -ComputerName $computername -filter "drivetype=3" |
  26. Where {$_.FreeSpace / $_.Size -lt $minpercent} |
  27. # Where {$_.FreeSpace / $_.Size -lt .1} | # 此处 .1表示10%
  28. Select -Property DeviceID,FreeSpace,Size

优化参数脚本

需要将-ComputerName参数变为强制参数,并给它一个名称为hostname的别名。并且使得脚本可以在运行命令之前和之后,显示详细输出。

  1. <#
  2. .SYNOPSIS
  3. Get physical network adapters.
  4. .DESCRIPTION
  5. 通过Win32_NetworkAdapter,获取全部的物理网卡信息。
  6. .PARAMETER computername
  7. The name of the computer to check.
  8. .EXAMPLE
  9. Get-PhysicalAdapter -computername SERVER-R2
  10. #>
  11. [CmdletBinding()]
  12. Param(
  13. [Parameter(Mandatory=$True, HelpMessage="Enter a computer name to query")]
  14. [Alias('hostname')]
  15. [string]$computername
  16. )
  17. Write-Verbose "Getting physical network adapters from $computername"
  18. Get-CimInstance Win32_NetworkAdapter -ComputerName $computer |
  19. Where-Object {$_.PhysicalAdapter} |
  20. Select-Object MACAddress, AdapterType, DeviceID, Name, Speed
  21. Write-Verbose "Script Finished!"

image.png

高级远程控制

在本地计算机创建一个名称为TestPoint的端点。将端点配置为仅自动载入SmbShare组件,但该组件只有Get-SmbShare命令可见。同时要确保类似Exit-PSSession的关键Cmdlet可见,但不允许使用其他核心PowerShell Cmdlet。
通过Enter-PSSession(指定localhost作为计算机名称,TestPoint作为配置名称)连接到该端口,对该端口进行测试。当连接成功后,运行Get-Command,从而确保只有少数配置为可见的命令可以被发现。

  1. # 创建会话配置文件
  2. PS C:\> New-PSSessionConfigurationFile -Path 'C:\itsTestEndpoint.pssc' -ModulesToImport SmbShare -SessionType RestrictedRemoteServer -CompanyName "IM30" -Author "Rick Guo" -Description "restricted SMBShare endpoint" -PowerShellVersion '5.0'
  3. # 注册配置
  4. # PS C:\> Register-PSSessionConfiguration -Path "C:\itsTestEndpoint.pssc" -RunAsCredential im30\rick -ShowSecurityDescriptorUI -Name TestPoint
  5. PS C:\> Register-PSSessionConfiguration -Path "C:\itsTestEndpoint.pssc" -Name TestPoint
  6. # 连接端点
  7. PS C:\> Enter-PSSession -ComputerName localhost -ConfigurationName TestPoint

使用正则

  1. 获取活动目录中所有名称包含两位数字的文件。
  2. 获得计算机中所有来自微软的进程,并显示进程ID、名称以及公司名称。提示:通过管道将Get-Process传递给Get-Member,从而显示属性名称。
  3. 在Windows Update日志中,该日志通常位于C:\Windows,你只希望显示代理开始安装文件的日志行。你或许需要在记事本中打开日志文件,从而找出你需要选择的字符串。
  4. 使用Get-DNSClientCache这个cmdlet显示列表,该列表仅显示Data属性为IPV4地址的条目。
    1. # 1.
    2. dir c:\windows | where {$_.name -match "\d{2}"}
    3. # 2.
    4. get-process | where {$_.company -match "^Microsoft"} | Select Name, ID, Company
    5. # 3.
    6. get-content C:\Windows\WindowsUpdate.log | Select-string "Start[\w+\W+]+Agent: Installing Updates"
    7. # 4.可以通过匹配以1~3位数字后跟着一个句号为开头的模式获得结果,如下:
    8. get-dnsclientcache | where { $_.data -match "^\d{1,3}\."}
    9. # 或者可以匹配整个IPv4地址字符串:
    10. get-dnsclientcache | where{ $_.data -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"}