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

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

有两个 cmdlet 可以获取 WMI 数据:旧的 Get-WmiObject cmdlet 和新的 Get-CimInstance cmdlet。当在本地使用时,两者的行为十分相像。然而当远程使用的时候,两者的区别十分明显。

以下是两个示例调用,分别从远程系统中获取共享的文件(请确保调整了计算机名):

1
2
Get-WmiObject -Class Win32_Share -ComputerName sr0710
Get-CimInstance -ClassName Win32_Share -ComputerName sr0710

(两个调用都需要目标计算机的本地的管理员权限,所以您可能需要添加 Credential 参数并且提交一个合法的账户名,如果您当前的用户不满足这些要求的话)

Get-WmiObject 总是使用 DCOM 做为传输协议,而 Get-CimInstance 使用 WSMAN(一种 WebService 类的通信协议)。多数主流的 Windows 操作系统支持 WSMan,但如果您需要和旧的服务器通信,它们可能只支持 DCOM,这样 Get-CimInstance 可能会失败。

Get-CimInstance 可以使用 session 参数,这提供了巨大的灵活性,而且运行您选择传输协议。要使用 DCOM(类似 Get-WmiObject),请使用以下代码:

1
2
3
4
$options = New-CimSessionOption -Protocol Dcom
$session = New-CimSession -ComputerName sr0710 -SessionOption $options
$sh = Get-CimInstance -ClassName Win32_Share -CimSession $session
Remove-CimSession -CimSession $session

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

WMI 是管理员的一个有用的信息源。您所需要的知识 WMI 类的名字,它代表了您感兴趣的东西。查找合法的 WMI 类名的最简单方法是搜索。

这行代码返回所有名字中包含 “Share” 的类:

1
Get-WmiObject -Class *share* -List

下一步,用 Get-WmiObject 获取一个类的所有实例:

1
Get-WmiObject -Class win32_share

如果您想查看所有属性,请别忘了将结果通过管道输出到 Select-Object 指令:

1
Get-WmiObject -Class win32_share | Select-Object -Property *

一个更好的方法是使用 Get-CimInstance 而不是 Get-WmiObject 因为它能自动转换数据类型,例如 DateTime

这个调用和 Get-WmiObject 的效果基本相同:

1
Get-CimInstance -ClassName Win32_Share

现在,您可以看到其中的区别:

1
2
3
4
5
Get-CimInstance -ClassName Win32_OperatingSystem |
Select-Object -Property Name, LastBootupTime, OSType

Get-WmiObject -Class Win32_OperatingSystem |
Select-Object -Property Name, LastBootupTime, OSType

PowerShell 技能连载 - 列出属性和值(第 3 部分)

当您希望检查单个对象和它的属性时,将对象用管道输出到 Out-GridView 指令不是太方便:网格视图窗口显示一个(非常长的)单行属性。试试这行代码,自己体验一下:

1
PS> Get-Process -Id $pid | Select-Object -Property * | Out-GridView

我们之前用过以下函数来对所有没有值的属性排序。但是这个函数还能做更多的事。他支持 -AsHashtable 参数,能将一个对象转换为哈希表,可以有效地帮助您显示单个对象的详细内容:

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
# Only list output fields with content

function Remove-EmptyProperty {
param (
[Parameter(Mandatory,ValueFromPipeline)]
$InputObject,

[Switch]
$AsHashTable
)


begin
{
$props = @()

}

process {
if ($props.COunt -eq 0)
{
$props = $InputObject |
Get-Member -MemberType *Property |
Select-Object -ExpandProperty Name |
Sort-Object
}

$notEmpty = $props | Where-Object {
!($InputObject.$_ -eq $null -or
$InputObject.$_ -eq '' -or
$InputObject.$_.Count -eq 0) |
Sort-Object

}

if ($AsHashTable)
{
$notEmpty |
ForEach-Object {
$h = [Ordered]@{}} {
$h.$_ = $InputObject.$_
} {
$h
}
}
else
{
$InputObject |
Select-Object -Property $notEmpty
}
}
}

当指定了 -AsHashtable 以后,Out-GridView 纵向显示对象内容,而不是水平显示。而且由于它叶移除了所有空白属性并按字母顺序对属性排序,它变得更容易查看和检视对象:

1
PS> Get-Process -Id $pid | Select-Object -Property * | Remove-EmptyProperty -AsHashTable | Out-GridView

例如把它用在 AD 用户对象上:

1
PS> Get-ADUser $env:username -Properties * | Remove-EmptyProperty -AsHashTable | Out-GridView