PowerShell 技能连载 - 使用免费的 PowerShell 陈列架(第 1 部分)

PowerShell 是一个可扩展的框架,并且 PowerShell 陈列架 (www.powershellgallery.com) 上有许多免费和有用的命令扩展。我们将在几个技能帖子中介绍这个陈列架的巨大功能。

要从 PowerShellGallery 中下载和安装任何扩展,您需要 PowerShellGet 模块,它提供了许多用于浏览、下载、安装、更新,和移除扩展的命令。

PowerShellGet 模块随着 PowerShell 5 分发,这是确认是否有该模块权限的方法:

1
2
3
4
5
6
7
8
9
PS> Get-Module PowerShellGet -ListAvailable


Directory: C:\Program Files\WindowsPowerShell\Modules


ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.0.0.1 PowerShellGet {Install-Module, Find-...

当您运行 PowerShell 5 时,您可能需要确认是否使用的是最终的版本。上一条命令汇报了已安装的版本。要检查陈列架中最新可用的版本,请试试这段代码:

1
2
3
4
5
PS> Find-Module PowerShellGet

Version Name Repository Description
------- ---- ---------- -----------
1.6.0 PowerShellGet PSGallery PowerShell...

要更新之前通过 PowerShell 陈列架安装的任意模块,您只需要运行 Update-Module,不过它对 PowerShellGet 运行失败:

1
2
PS> Update-Module PowerShellGet
Update-Module : Module 'PowerShellGet' was not installed by using Install-Module, so it cannot be updated.

这是因为该模块是随着 Windows 10 分发,您需要手工重新安装该模块。如果您有管理员权限,强烈建议先打开一个提升权限的 PowerShell,然后基于它安装(更新)以下的包:

1
2
3
4
5
PS> Install-PackageProvider Nuget –Force

Name Version Source Summary
---- ------- ------ -------
nuget 2.8.5.208 https://onege... N...

如果您没有事先更新包管理器,您坑无法更新 PowerShellGet 模块。当您更新了包管理器之后,请关闭所有 PowerShell 窗口,并打开一个全新的 PowerShell 控制台,以确保它使用新的包管理器。

下一步,安装最新版本的 PowerShellGet:

1
PS> Install-Module –Name PowerShellGet –Force

如果您没有管理员权限,那么用 -Scope CurrentUser 参数只为当前用户安装 PowerShellGet。

您现在可以在已有版本之外独立使用最新本的 PowerShellGet:

1
2
3
4
5
6
7
8
9
10
PS> Get-Module PowerShellGet -ListAvailable


Directory: C:\Program Files\WindowsPowerShell\Modules


ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 1.6.0 PowerShellGet {Install-Module, Find-Module...
Script 1.0.0.1 PowerShellGet {Install-Module, Find-Module...

您现在可以完美地通过 Update-Module(使用您安装它时相同的权限)更新模块:

1
PS> Update-Module PowerShellGet

这下您的指尖又多列一些命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
PS> Get-Command -Module PowerShellGet

CommandType Name Version Sou
rce
----------- ---- ------- ---
Function Find-Command 1.6.0 Pow
Function Find-DscResource 1.6.0 Pow
Function Find-Module 1.6.0 Pow
Function Find-RoleCapability 1.6.0 Pow
Function Find-Script 1.6.0 Pow
Function Get-InstalledModule 1.6.0 Pow
Function Get-InstalledScript 1.6.0 Pow
Function Get-PSRepository 1.6.0 Pow
Function Install-Module 1.6.0 Pow
Function Install-Script 1.6.0 Pow
Function New-ScriptFileInfo 1.6.0 Pow
Function Publish-Module 1.6.0 Pow
Function Publish-Script 1.6.0 Pow
Function Register-PSRepository 1.6.0 Pow
Function Save-Module 1.6.0 Pow
Function Save-Script 1.6.0 Pow
Function Set-PSRepository 1.6.0 Pow
Function Test-ScriptFileInfo 1.6.0 Pow
...

PowerShell 技能连载 - PowerShell 中打印表格(使用 WPF)

当您需要以表格的形式显示、打印,或保存为 PDF,使用 WPF (Windows Presentation Foundation) 可能是一种好方法。以前,WPF 是用于定义用户界面,但是您可以用它来定义表格,填充数据,然后打印或者保存它们。

不要因为代码量而拖延。PowerShell 基本上是以面向对象的方式定义表格。

以下示例代码创建一个模块中所有命令的文档。您可以方便地改变代码创建更多列以及更多其他数据的表格。当您运行以下代码时,它打开一个选择打印机的对话框。选择 “Microsoft Print to PDF” 打印机,将输出结果保存为一个 PDF 文档。

请注意:当您在 PowerShell ISE(或任何其它基于 WPF 的编辑器)中运行这段代码,将无法显示打印机对话框,并且将自动打印到缺省的打印机中。当您在 powershell.exe 中运行这段代码,一切正常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# adjust the name of the module
# code will list all commands shipped by that module
# list of all modules: Get-Module -ListAvailable
$ModuleName = "PrintManagement"


# these assemblies provide access to UI
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName PresentationFramework

# create a new document
$document = [System.Windows.Documents.FlowDocument]::new()

# create a new table with two columns (20%, 80% width)
$table = [System.Windows.Documents.Table]::new()
$column1 = [System.Windows.Documents.TableColumn]::new()
$column1.Width = [System.Windows.GridLength]::new(20, [System.Windows.GridUnitType]::Star)
$table.Columns.Add($column1)
$column2 = [System.Windows.Documents.TableColumn]::new()
$column2.Width = [System.Windows.GridLength]::new(80, [System.Windows.GridUnitType]::Star)
$table.Columns.Add($column2)

# create a new rowgroup that will store the table rows
$rowGroup = [System.Windows.Documents.TableRowGroup]::new()


# produce the command data to display in the table
Get-Command -Module $moduleName |
Get-Help |
ForEach-Object {
# get the information to be added to the table
$name = $_.Name
$synopsis = $_.Synopsis
$description = $_.Description.Text -join ' '

# create a new table row
$row = [System.Windows.Documents.TableRow]::new()

# add a cell with the command name in bold:
$cell = [System.Windows.Documents.TableCell]::new()
$cell.Padding = [System.Windows.Thickness]::new(0,0,10,0)
$para = [System.Windows.Documents.Paragraph]::new()
$inline = [System.Windows.Documents.Run]::new($name)
$inline.FontWeight = "Bold"
$inline.FontSize = 12
$inline.FontFamily = "Segoe UI"
$para.Inlines.Add($inline)
$cell.AddChild($para)
$row.AddChild($cell)

# add a second cell with the command synopsis
$cell = [System.Windows.Documents.TableCell]::new()
$para = [System.Windows.Documents.Paragraph]::new()
$inline = [System.Windows.Documents.Run]::new($synopsis)
$inline.FontSize = 12
$inline.FontFamily = "Segoe UI"
$para.Inlines.Add($inline)
$cell.AddChild($para)
$row.AddChild($cell)

# add both cells to the table
$rowGroup.AddChild($row)

# add a second table row than spans two columns and holds the
# command description in a smaller font:
$row = [System.Windows.Documents.TableRow]::new()
$cell = [System.Windows.Documents.TableCell]::new()
$cell.ColumnSpan = 2
# add a 20pt gap at the bottom to separate from next command
$cell.Padding = [System.Windows.Thickness]::new(0,0,0,20)
$para = [System.Windows.Documents.Paragraph]::new()
$inline = [System.Windows.Documents.Run]::new($description)
$inline.FontSize = 10
$inline.FontFamily = "Segoe UI"
$para.Inlines.Add($inline)
$cell.AddChild($para)
$row.AddChild($cell)
# add row to table:
$rowGroup.AddChild($row)
}

# add all collected table rows to the table, and add the table
# to the document
$table.AddChild($rowGroup)
$document.AddChild($table)

# add a paginator that controls where pages end and new pages start:
[System.Windows.Documents.IDocumentPaginatorSource]$paginator = $document

# create a print dialog to select the printer
$printDialog = [System.Windows.Controls.PrintDialog]::new()
# print dialog can not be shown in ISE due to threading issues
# selecting a printer will work only when running this code in powershell.exe
# else, the default printer is used
try
{
$result = $printDialog.ShowDialog()
if ($result -eq $false) {
Write-Warning "User aborted."
return
}
}
catch {}

# make sure the document is not printed in multiple columns
$document.PagePadding = [System.Windows.Thickness]::new(50)
$document.ColumnGap = 0
$document.ColumnWidth = $printDialog.PrintableAreaWidth

# print the document
$printDialog.PrintDocument($paginator.DocumentPaginator, "WPF-Printing from PowerShell")

PowerShell 技能连载 - 创建 PowerShell 命令速查表(第 4 部分)

在前一个技能里,我们创建了 PowerShell 命令的速查表。我们使用了它的名称和提要来创建速查表,类似这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
PS> Get-Command -Module "PrintManagement"|
Get-Help |
Select-Object -Property Name, Synopsis

Name Synopsis
---- --------
Add-Printer Adds a printer to the specified computer.
Add-PrinterDriver Installs a printer driver on the specified computer.
Add-PrinterPort Installs a printer port on the specified computer.
Get-PrintConfiguration Gets the configuration information of a printer.
Get-Printer Retrieves a list of printers installed on a computer.
Get-PrinterDriver Retrieves the list of printer drivers installed on...
Get-PrinterPort Retrieves a list of printer ports installed on the...
Get-PrinterProperty Retrieves printer properties for the specified pri...
Get-PrintJob Retrieves a list of print jobs in the specified pr...
Read-PrinterNfcTag Reads information about printers from an NFC tag.
Remove-Printer Removes a printer from the specified computer.
Remove-PrinterDriver Deletes printer driver from the specified computer.
Remove-PrinterPort Removes the specified printer port from the specif...
Remove-PrintJob Removes a print job on the specified printer.
...

Get-Help 返回的结果中有许多更有用的属性,例如 “description“ 和 “examples“。不过它们看起来很奇怪,好像装在一个哈希表中一样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
PS> Get-Command -Module "PrintManagement"|
Get-Help |
Select-Object -Property Name, Description

Name description
---- -----------
Add-Printer {@{Text=The Add-Printer cmdlet adds a printer to a specified computer. Y...
Add-PrinterDriver {@{Text=The Add-PrinterDriver cmdlet installs a printer driver on the sp...
Add-PrinterPort {@{Text=The Add-PrinterPort cmdlet creates a printer port on the specifi...
Get-PrintConfiguration {@{Text=The Get-PrintConfiguration cmdlet gets the configuration informa...
Get-Printer {@{Text=The Get-Printer cmdlet retrieves a list of printers installed on...
Get-PrinterDriver {@{Text=The Get-PrinterDriver cmdlet retrieves the list of printer drive...
Get-PrinterPort {@{Text=The Get-PrinterPort cmdlet retrieves a list of printer ports tha...
Get-PrinterProperty {@{Text=The Get-PrinterProperty cmdlet retrieves one or more printer pro...
Get-PrintJob {@{Text=The Get-PrintJob cmdlet retrieves the current print jobs in the ...
Read-PrinterNfcTag {@{Text=The Read-PrinterNfcTag cmdlet reads information about printers f...
Remove-Printer {@{Text=The Remove-Printer cmdlet deletes a printer from the specified c...
Remove-PrinterDriver {@{Text=The Remove-PrinterDriver cmdlet deletes a printer driver from th...
Remove-PrinterPort {@{Text=The Remove-PrinterPort cmdlet removes the specified printer port...
...

这是因为类似 “Description” 的属性包含了一个名为 “Text“ 的属性,它是一个数组(支持多行文本)。要获取纯文本,您需要手工从属性获取信息,类似这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
# adjust the name of the module
# code will list all commands shipped by that module
# list of all modules: Get-Module -ListAvailable
$ModuleName = "PrintManagement"

$Description = @{
Name = "Description"
Expression = { $_.Description.Text -join " " }
}

Get-Command -Module $moduleName |
Get-Help |
Select-Object -Property Name, $Description

现在结果看起来和预期相符了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Name                   Description
---- -----------
Add-Printer The Add-Printer cmdlet adds a printer to a specified ...
Add-PrinterDriver The Add-PrinterDriver cmdlet installs a printer drive...
Add-PrinterPort The Add-PrinterPort cmdlet creates a printer port on ...
Get-PrintConfiguration The Get-PrintConfiguration cmdlet gets the configurat...
Get-Printer The Get-Printer cmdlet retrieves a list of printers i...
Get-PrinterDriver The Get-PrinterDriver cmdlet retrieves the list of pr...
Get-PrinterPort The Get-PrinterPort cmdlet retrieves a list of printe...
Get-PrinterProperty The Get-PrinterProperty cmdlet retrieves one or more ...
Get-PrintJob The Get-PrintJob cmdlet retrieves the current print j...
Read-PrinterNfcTag The Read-PrinterNfcTag cmdlet reads information about...
Remove-Printer The Remove-Printer cmdlet deletes a printer from the ...
Remove-PrinterDriver The Remove-PrinterDriver cmdlet deletes a printer dri...
Remove-PrinterPort The Remove-PrinterPort cmdlet removes the specified p...
Remove-PrintJob The Remove-PrintJob cmdlet removes a print job on the...
Rename-Printer The Rename-Printer cmdlet renames the specified print...
Restart-PrintJob The Restart-PrintJob cmdlet restarts a print job on t...
Resume-PrintJob The Resume-PrintJob cmdlet resumes a suspended print ...
Set-PrintConfiguration The Set-PrintConfiguration cmdlet sets the printer co...
Set-Printer The Set-Printer cmdlet updates the configuration of t...

PowerShell 技能连载 - 创建 PowerShell 命令速查表(第 3 部分)

在前一个技能中,我们创建了 PowerShell 命令的速查表并且将他们转换为可被浏览器打开和打印的 HTML 报告。它可以正常工作,但是输出页面不是非常精致。只要加上一些 HTML 延时,您的命令列表就可以上黄金档啦,而且您还可以用这个例子中的技术来“美化”任何通过 PowerShell 的 ConvertTo-Html 创建的 HTML 表格:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# adjust the name of the module
# code will list all commands shipped by that module
# list of all modules: Get-Module -ListAvailable
$ModuleName = "PrintManagement"
$Title = "PowerShell Print Management Commands"
$OutFile = "$env:temp\commands.html"
$StyleSheet = @"
<title>$Title</title>
<style>
h1, th { text-align: center; font-family: Segoe UI; color:#0046c3;}
table { margin: auto; font-family: Segoe UI; box-shadow: 10px 10px 5px #888; border: thin ridge grey; }
th { background: #0046c3; color: #fff; max-width: 400px; padding: 5px 10px; }
td { font-size: 11px; padding: 5px 20px; color: #000; }
tr { background: #b8d1f3; }
tr:nth-child(even) { background: #dae5f4; }
tr:nth-child(odd) { background: #b8d1f3; }
</style>
"@
$Header = "<h1 align='center'>$title</h1>"
Get-Command -Module $moduleName |
Get-Help |
Select-Object -Property Name, Synopsis |
ConvertTo-Html -Title $Title -Head $StyleSheet -PreContent $Header |
Set-Content -Path $OutFile


Invoke-Item -Path $OutFile

PowerShell 技能连载 - 创建 PowerShell 命令速查表(第 2 部分)

在前一个技能中,我们创建了 PowerShell 命令的速查表,在此提醒,这行代码将会创建网络命令的速查表(假设您有存取本例中 NetAdapter 模块的权限):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
PS> Get-Command -Module NetAdapter | Get-Help | Select-Object -Property Name, Synopsis

Name Synopsis
---- --------
Disable-NetAdapter Disables a network adapter.
Disable-NetAdapterBinding Disables a binding to a netw...
Disable-NetAdapterChecksumOffload Disables the selected checks...
Disable-NetAdapterEncapsulatedPacketTaskOffload Disables encapsulated packet...
Disable-NetAdapterIPsecOffload Disables IPsec offload on th...
Disable-NetAdapterLso Disables all LSO properties,...
Disable-NetAdapterPacketDirect ...
Disable-NetAdapterPowerManagement Disables specific power mana...
Disable-NetAdapterQos Disables QoS on a network ad...
Disable-NetAdapterRdma Disables RDMA on a network a...
Disable-NetAdapterRsc Disables RSC on a network ad...
Disable-NetAdapterRss Disables RSS on a network ad...
Disable-NetAdapterSriov Disables SR-IOV on a network...
Disable-NetAdapterVmq Disables the VMQ feature on ...
Enable-NetAdapter Enables a network adapter.
Enable-NetAdapterBinding Enables binding of a protoco...
Enable-NetAdapterChecksumOffload Enables checksum offloads on...
Enable-NetAdapterEncapsulatedPacketTaskOffload Enables encapsulated packet ...
Enable-NetAdapterIPsecOffload Enables IPsec offload on the...
Enable-NetAdapterLso Enables LSO properties, such...
Enable-NetAdapterPacketDirect ...
Enable-NetAdapterPowerManagement Enables specific power manag...
Enable-NetAdapterQos Enables QoS on the network a...
Enable-NetAdapterRdma Enables RDMA on a network ad...
Enable-NetAdapterRsc Enables RSC on a network ada...
Enable-NetAdapterRss Enables RSS on a network ada...
Enable-NetAdapterSriov Enables SR-IOV on a network ...
Enable-NetAdapterVmq Enables VMQ on a network ada...
Get-NetAdapter Gets the basic network adapt...
Get-NetAdapterAdvancedProperty Gets the advanced properties...
Get-NetAdapterBinding Gets a list of bindings for ...
Get-NetAdapterChecksumOffload Gets the various checksum of...
Get-NetAdapterEncapsulatedPacketTaskOffload Gets the network adapters th...
...

要让这个列表更有价值,让我们将它转换为 HTML 表格,这样您可以在浏览器中打开,并且打印:

1
2
3
4
5
6
7
8
9
10
11
12
$ModuleName = "NetAdapter"
$OutFile = "$env:temp\commands.html"


Get-Command -Module $moduleName |
Get-Help |
Select-Object -Property Name, Synopsis |
ConvertTo-Html |
Set-Content -Path $OutFile


Invoke-Item -Path $OutFile

运行这段代码后,几秒钟后您的缺省 WEB 浏览器将会打开一个包含速查表信息的页面。现在可以用浏览器的命令来打印它。这个页面不是十分美观,但满足了它的需求。

PowerShell 技能连载 - 创建 PowerShell 命令速查表(第 1 部分)

以下是一个创建您喜爱的 PowerShell 命令的速查表的的技巧。

所有 PowerShell 命令都是随着模块分发,所以如果您认为某个 PowerShell 对您有用,您可能希望列出模块中其它(可能相关)的命令。这行代码显示如何查找任何指定命令的模块名,并列出包含 Get-WmiObject 命令的模块名:

1
2
3
PS>
PS> (Get-Command -Name Get-WmiObject).ModuleName
Microsoft.PowerShell.Management

要查看这个模块所有其它命令,请试试这段代码:

1
2
3
4
5
6
7
8
9
10
11
12
PS> Get-Command -Module Microsoft.PowerShell.Management

CommandType Name Version
----------- ---- -------
Cmdlet Add-Computer 3.1.0.0
Cmdlet Add-Content 3.1.0.0
Cmdlet Checkpoint-Computer 3.1.0.0
Cmdlet Clear-Content 3.1.0.0
Cmdlet Clear-EventLog 3.1.0.0
Cmdlet Clear-Item 3.1.0.0
Cmdlet Clear-ItemProperty 3.1.0.0
Cmdlet Clear-RecycleBin 3.1.0.0

要创建一个包含命令名和描述的便利的速查表,请将命令通过管道导出到 Get-Help 命令,然后使用 Select-Object 从帮助中选择详细信息,加入您的速查表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
PS> Get-Command -Module Microsoft.PowerShell.Management | Get-Help | Select-Object -Property Name, Synopsis

Name Synopsis
---- --------
Add-Computer Add the local computer to a domain or workgroup.
Add-Content Adds content to the specified items, such as adding word...
Checkpoint-Computer Creates a system restore point on the local computer.
Clear-Content Deletes the contents of an item, but does not delete the...
Clear-EventLog Clears all entries from specified event logs on the loca...
Clear-Item Clears the contents of an item, but does not delete the ...
Clear-ItemProperty Clears the value of a property but does not delete the p...
Clear-RecycleBin
Complete-Transac... Commits the active transaction.
Convert-Path Converts a path from a Windows PowerShell path to a Wind...
Copy-Item Copies an item from one location to another.
Copy-ItemProperty Copies a property and value from a specified location to...
Debug-Process Debugs one or more processes running on the local computer.
Disable-Computer... Disables the System Restore feature on the specified fil...
Enable-ComputerR... Enables the System Restore feature on the specified file...
Get-ChildItem Gets the items and child items in one or more specified ...
Get-Clipboard Gets the current Windows clipboard entry.
Get-ComputerInfo Gets a consolidated object of system and operating syste...
Get-ComputerRest... Gets the restore points on the local computer.
Get-Content Gets the content of the item at the specified location.
Get-ControlPanel... Gets control panel items.
Get-EventLog Gets the events in an event log, or a list of the event ...
Get-HotFix Gets the hotfixes that have been applied to the local an...
Get-Item Gets the item at the specified location.
Get-ItemProperty Gets the properties of a specified item.
Get-ItemProperty... Gets the value for one or more properties of a specified...
Get-Location Gets information about the current working location or a...

如果帮助信息不完整,并且没有选择的命令没有提要信息,那么您可能首先需要下载 PowerShell 帮助。要下载帮助,首先需要一个提升权限的 PowerShell:

1
PS> Update-Help -UICulture en-us -Force

不要担心这条命令抛出的错误信息:它对于一小部分没有提供帮助信息的模块是正常的。如果您收到一大堆错误信息,那么您可能没有在提升权限的 PowerShell 中执行命令。不幸的是,PowerShell 存储帮助文件的位置和模块的位置不同,普通用户不可存存储取帮助文件的位置。

PowerShell 技能连载 - 通过 Windows 10 开始菜单快速打开 PowerShell

在 Windows 10 中,PowerShell 可以通过 WIN + X 键(或右键单击开始菜单图标)启动。如果您的 Windows 10 打开的是过时的 cmd.exe,那么该快速做出改变了。

单击开始菜单图标(或按 WIN 键)。在开始菜单中,单击“齿轮”图标打开 Windows 设置。您现在可以看到一个有许多图标的,名为“Windows 设置”的窗口,在顶部有一个叫做“查找设置”的文本框。在文本框中输入 “PowerShell” 即可打开“使用 Windows + X 菜单时,将命令提示符替换为 Windows PowerShell”。

PowerShell 技能连载 - 测试 AD 用户是否存在

如果您需要查看一个指定的域用户是否存在,并且假设您已经安装了 ActiveDirectory PowerShell 模块,它是 RSAT(远程服务器管理工具)的一部分,那么有一个更巧的方法:

1
2
3
4
5
6
7
8
9
10
11
12
function Test-UserExists
{
param
(
[Parameter(Mandatory)]
[string]
$SAMAccountName
)

@(Get-ADUser -LDAPFilter "(samaccountname=$SAMAccountName)").Count -ne 0

}

您也可以调整 LDAP 查询来基于其它属性检查用户。

PowerShell 技能连载 - WMI 快速入门(第 4 部分)

通常,WMI 对象有许多包含重要信息的属性。这行代码将获取所有运行中的记事本实例的所有信息(请先运行记事本):

1
2
3
4
5
6
7
Get-WmiObject -Class Win32_Process -Filter 'Name LIKE "%notepad%"'
···

类似的,这行代码用 `Get-CimInstance` 获取相同的信息:

```powershell
Get-CimInstance -Class Win32_Process -Filter 'Name LIKE "%notepad%"'

有些时候,WMI 对象也包含方法。获取方法名最简单的方法是用 Get-WmiObject,然后将结果通过管道传送给 Get-Member 命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PS> Get-WmiObject -Class Win32_Process -Filter 'Name LIKE "%notepad%"' | Get-Member -MemberType *method


TypeName: System.Management.ManagementObject#root\cimv2\Win32_Process

Name MemberType Definition
---- ---------- ----------
AttachDebugger Method System.Management.ManagementBaseObject AttachDebugger()
GetAvailableVirtualSize Method System.Management.ManagementBaseObject GetAvailableVirtualSize()
GetOwner Method System.Management.ManagementBaseObject GetOwner()
GetOwnerSid Method System.Management.ManagementBaseObject GetOwnerSid()
SetPriority Method System.Management.ManagementBaseObject SetPriority(System.Int32 Priority)
Terminate Method System.Management.ManagementBaseObject Terminate(System.UInt32 Reason)
ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime();
ConvertToDateTime ScriptMethod System.Object ConvertToDateTime();

要调用一个方法,例如获取一个进程的所有者时,Get-WmiObjectGet-CimInstance 之间有一个基本的区别:

当您通过 Get-WmiObject 获取对象时,对象的方法是返回对象的一部分:

1
2
3
4
$notepads = Get-WmiObject -Class Win32_Process -Filter 'Name LIKE "%notepad%"'
$notepads | ForEach-Object {
$notepads.GetOwner()
}

通过 Get-CimInstance 返回的对象不包含 WMI 方法。要调用 WMI 方法,您需要调用 Invoke-CimMethod

1
2
3
4
5
$notepads = Get-CimInstance -Class Win32_Process -Filter 'Name LIKE "%notepad%"'
$notepads |
ForEach-Object {
Invoke-CimMethod -InputObject $_ -MethodName "GetOwner"
}

在以上的代码中,假设您移除 GetOwner,而是按下 CTRL + SPACE 键调出智能感知(或在简单 PowerShell 控制台中按 TAB 键),您可以获得所有可用的方法名称。如果一个方法需要参数,请使用 -Arguments 参数。

PowerShell 技能连载 - WMI 快速入门(第 3 部分)

在前一个技能中我们解释了为什么 Get-CimInstance 比旧的 Get-WmiObject cmdlet 有优势。

这是另一个例子,演示了为什么 Get-CimInstance 可能会比 Get-WmiObject 快得多。

当您需要从远程主机查询多个 WMI 类,例如您需要创建一个库存报告,每次运行 cmdlet 时 Get-WmiObject 需要连接和断开连接。然而 Get-CimInstance 可以复用已有的 session。

以下是一个演示如何在两个查询中复用同一个 session 的例子:

1
2
3
4
5
6
7
8
9
10
# create the session
$options = New-CimSessionOption -Protocol Wsman
$session = New-CimSession -ComputerName sr0710 -SessionOption $options

# reuse the session for as many queries as you like
$sh = Get-CimInstance -ClassName Win32_Share -CimSession $session -Filter 'Name="Admin$"'
$se = Get-CimInstance -ClassName Win32_Service -CimSession $session

# remove the session at the end
Remove-CimSession -CimSession $session

当您需要连接到不支持 WSMan 的旧的计算机,只需要将以上代码的协议改为 DCOM 即可:将 Wsman 替换为 Dcom