PowerShell 技能连载 - 修复 PowerShell 5 帮助的 Bug

使用 Update-Help 下载 PowerShell 的帮助文件时,PowerShell 5 有一个 bug,目前可以修复:基于文本的帮助文件扩展名是“.txt”而不是“.help.txt”,所以 PowerShell 帮助系统会忽略它们。您可以自己试验一下——以下命令可能会返回一大堆关于主题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
PS C:\> Get-Help about*

Name Category Module Synopsis
---- -------- ------ --------
about_Aliases HelpFile SHORT DESCRIPTION
about_Arithmetic_Operators HelpFile SHORT DESCRIPTION
about_Arrays HelpFile SHORT DESCRIPTION
about_Assignment_Operators HelpFile SHORT DESCRIPTION
about_Automatic_Variables HelpFile SHORT DESCRIPTION
about_Break HelpFile SHORT DESCRIPTION
about_Classes HelpFile SHORT DESCRIPTION
about_Command_Precedence HelpFile SHORT DESCRIPTION
about_Command_Syntax HelpFile SHORT DESCRIPTION
about_Comment_Based_Help HelpFile SHORT DESCRIPTION
about_CommonParameters HelpFile SHORT DESCRIPTION
about_Comparison_Operators HelpFile SHORT DESCRIPTION
about_Continue HelpFile SHORT DESCRIPTION
about_Core_Commands HelpFile SHORT DESCRIPTION
about_Data_Sections HelpFile SHORT DESCRIPTION
about_Debuggers HelpFile SHORT DESCRIPTION
about_DesiredStateConfiguration HelpFile SHORT DESCRIPTION

如果没有显示上述的内容,您也许还没有事先运行过 Update-Help 来下载帮助文件,或者您被 bug 吃了。

无论这个 bug 是否正在修复中,用 PowerShell 您可以轻松地修改这些东西。以下是一个用于修复这些受影响的帮助文件的扩展名的脚本。

这个脚本需要管理员权限,因为帮助文件是位于受保护的 Windows 文件夹中:

1
2
3
4
5
6
7
# find all text files inside the PowerShell folder that start
# with "about"
Get-ChildItem -Path $pshome -Filter about*.txt -Recurse |
# identify those that do not end with ".help.txt"
Where-Object { $_.Name -notlike '*.help.txt' } |
# rename the extension using a regex:
Rename-Item -NewName { $_.Name -replace '\.txt$', '.help.txt'}

PowerShell 技能连载 - 禁止按位置的参数

当您创建 PowerShell 函数时,参数可以是命名的也可以是按位置的。以下是一个例子:

如果您想检测文件系统中的非法字符,以下是一个简单的适配:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Test-Command
{
param
(
[string]$Name,
[int]$Id
)

"Name: $Name ID: $ID"
}

Test-Command -Name Weltner -Id 12
Test-Command Weltner 12

如您所见,使用按位置的参数(只需要指定参数,不需要显式地指定参数名)可能更适用于为特定目的编写的代码,但是可读性更差。这是有可能的,因为上述函数的语法看起来如下:

1
Test-Command [[-Name] <string>] [[-Id] <int>]

那么一个编写一个效果相反的 PowerShell 函数,实现这种语法呢:

1
Test-Command [-Name <string>] [-Id <int>] [<CommonParameters>]

目前这个方法比较生僻,不过是完全可行的:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Test-Command
{
param
(
[Parameter(ParameterSetName='xy')]
[string]$Name,

[Parameter(ParameterSetName='xy')]
[int]$Id
)

"Name: $Name ID: $ID"
}

一旦开始使用参数集合,缺省情况下所有参数都是命名的参数。

PowerShell 技能连载 - 在 PowerShell 函数中使用命名的函数

当您创建一个 PowerShell 函数时,所有参数都有默认的位置,除非人为地加上“Position”属性。一旦加上这个属性,所有不带“Position”的参数将立刻变为命名的必须参数。让我们看看例子:

这是一个经典的函数定义,创建了三个固定位置的参数:

1
2
3
4
5
6
7
8
9
10
11
function Test-Command
{
param
(
[string]$Name,
[int]$ID,
[string]$Email
)

# TODO: Code using the parameter values
}

语法如下:

1
Test-Command [[-Name] <string>] [[-ID] <int>] [[-Email] <string>]

一旦您在任何一个参数上添加“Position”属性,其它的就变为命名的参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Test-Command
{
param
(
[Parameter(Position=0)]
[string]$Name,
[Parameter(Position=1)]
[int]$ID,
[string]$Email
)

# TODO: Code using the parameter values
}

以下是它的语法:

1
Test-Command [[-Name] <string>] [[-ID] <int>] [-Email <string>] [<CommonParameters>]

区别在哪?您不需要指定参数名 -Name-ID,但如果您希望为第三个参数指定一个值,必须指定 -Email。在第一个例子中,所有三个参数都可以按照位置来定位。

PowerShell 技能连载 - 隐藏启动 PowerShell

有时候 PowerShell 脚本只是用来生成某些东西,比如说生成报告,而不需要用 Excel 或记事本打开它。这时候您不会希望执行 PowerShell 的时候显示 PowerShell 控制台窗口。

并没有很简单的方法能隐藏 PowerShell 的控制台窗口,因为即使用了 -WindowsStyle Hidden 参数,也会先显示控制台,然后隐藏它(一闪而过)。

一种方法是使用 Windows 快捷方式来启动脚本。右键单击桌面的空白区域,然后选择新建/快捷方式。就可以新建一个快捷方式。当提示输入地址的时候,键入这行代码:

1
powershell -noprofile -executionpolicy bypass -file "c:\path\to\script.ps1"

点击“下一步”,然后添加脚本的名称,再点击“下一步”,就接近完成了。这个快捷方式显示蓝色的 PowerShell 图标。单击它的时候,脚本即可运行,只是还不是隐藏的。

您现在只需要右键单击新创建的快捷方式,选择“属性”,然后将“运行”的设置从“正常窗口”改为您想要的设置。您也可以设置一个快捷方式,这需要管理员权限。

一个缺点是,在 Windows 10 中,“运行”的设置不再包含隐藏程序的选项。您最多可以最小化执行。

PowerShell 技能连载 - PowerShell 5.1 中的时区管理

PowerShell 5.1(随 Windows 10 和 Server 2016 发布)带来一系列管理计算机时区的新 cmdlet。Get-TimeZone 返回当前的设置,而 Set-TimeZone 可以改变时区设置:

PS C:\> Get-TimeZone

Id                         : W. Europe Standard Time
DisplayName                : (UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm,
                             Vienna
StandardName               : W. Europe Standard Time
DaylightName               : W. Europe Daylight Time
BaseUtcOffset              : 01:00:00
SupportsDaylightSavingTime : True

PowerShell 技能连载 - 探索函数源码

在 PowerShell 中,cmdlet 和 function 的唯一根本区别是它们是怎么编程的:函数用的是纯粹的 PowerShell 代码,这也是查看它们的源代码,并学习新东西的有趣之处。

这行代码列出所有当前从 module 中加载的所有 PowerShell function:

1
Get-Module | ForEach-Object { Get-Command -Module $_.Name -CommandType Function }

一旦您知道了内存中某个函数的名字,可以用这种方法快捷查看它的源代码。在这些例子中,我们将探索 Format-Hex 函数。只需要将这个名字替换成内存中存在的其它函数名即可:

1
${function:Format-Hex} | clip.exe

这行代码将源代码存入剪贴板,您可以将它粘贴到您喜欢的编辑器中。另外,您也可以用这种方式运行:

1
2
3
Get-Command -Name Format-Hex -CommandType Function |
Select-Object -ExpandProperty Definition |
clip.exe

PowerShell 技能连载 - 在同一台机器上运行 32 位代码

如果您需要在 64 位脚本中运行 32 位 PowerShell 代码,假设您是管理员,并且使用远程操作功能,您可以远程操作您的系统:

1
2
3
4
5
6
7
$code = {
[IntPtr]::Size
Get-Process
}


Invoke-Command -ScriptBlock $code -ConfigurationName microsoft.powershell32 -ComputerName $env:COMPUTERNAME

这将在 32 位环境中运行 $code 中的脚本块。该指针返回的 size 是 4,这是 32 位的证据。当您直接运行脚本块,返回的是 8 字节(64 比特)。

PowerShell 技能连载 - systeminfo.exe 的最新替代

曾几何时,systeminfo.exe 返回一台电脑所有的分析信息,并且有一些能够在 PowerShell 中变成面向对象的:

PS C:\> $info = systeminfo.exe /FO CSV | ConvertFrom-Csv

PS C:\> $info.Domain
WORKGROUP

PS C:\> $info.'Logon Server'
\\DESKTOP-7AAMJLF

在 PowerShell 5.1 (Windows 10 和 Server 2016 )中,有一个现代的替代品:

PS C:\> Get-ComputerInfo


WindowsBuildLabEx                                       : 14393.321.amd64fre.rs1_release_inmarket.161004-2338
WindowsCurrentVersion                                   : 6.3
WindowsEditionId                                        : Professional
WindowsInstallationType                                 : Client
WindowsInstallDateFromRegistry                          : 8/17/2016 1:40:27 PM
WindowsProductId                                        : 00350-50721-50845-ACOEM
WindowsProductName                                      : Windows 10 Pro
WindowsRegisteredOrganization                           :
WindowsRegisteredOwner                                  : topoftheworld
WindowsSystemRoot                                       : C:\WINDOWS
BiosCharacteristics                                     : {7, 9, 11, 12...}
BiosBIOSVersion                                         : {DELL   - 1072009, 1.4.4, American Megatrends - 5000B}
BiosBuildNumber                                         :
BiosCaption                                             : 1.4.4
BiosCodeSet                                             :
BiosCurrentLanguage                                     : en|US|iso8859-1
BiosDescription                                         : 1.4.4
BiosEmbeddedControllerMajorVersion                      : 255
BiosEmbeddedControllerMinorVersion                      : 255
BiosFirmwareType                                        : Uefi
BiosIdentificationCode                                  :
BiosInstallableLanguages                                : 2
BiosInstallDate                                         :
BiosLanguageEdition                                     :
BiosListOfLanguages                                     : {en|US|iso8859-1, }
BiosManufacturer                                        : Dell Inc.
BiosName                                                : 1.4.4
BiosOtherTargetOS                                       :
BiosPrimaryBIOS                                         : True
BiosReleaseDate                                         : 6/14/2016 2:00:00 AM
BiosSeralNumber                                         : DLGQD72
BiosSMBIOSBIOSVersion                                   : 1.4.4
BiosSMBIOSMajorVersion                                  : 2
BiosSMBIOSMinorVersion                                  : 8
BiosSMBIOSPresent                                       : True
BiosSoftwareElementState                                : Running
BiosStatus                                              : OK
BiosSystemBiosMajorVersion                              : 1
BiosSystemBiosMinorVersion                              : 4
BiosTargetOperatingSystem                               : 0
BiosVersion                                             : DELL   - 1072009
CsAdminPasswordStatus                                   : Unknown
CsAutomaticManagedPagefile                              : True
CsAutomaticResetBootOption                              : True
CsAutomaticResetCapability                              : True
CsBootOptionOnLimit                                     :
CsBootOptionOnWatchDog                                  :
CsBootROMSupported                                      : True
CsBootStatus                                            : {0, 0, 0, 0...}
CsBootupState                                           : Normal boot
CsCaption                                               : CLIENT
CsChassisBootupState                                    : Safe
CsChassisSKUNumber                                      : Laptop
CsCurrentTimeZone                                       : 120
CsDaylightInEffect                                      : True
CsDescription                                           : AT/AT COMPATIBLE
CsDNSHostName                                           : DESKTOP-7AAMJLF
CsDomain                                                : WORKGROUP
CsDomainRole                                            : StandaloneWorkstation
CsEnableDaylightSavingsTime                             : True
CsFrontPanelResetStatus                                 : Unknown
CsHypervisorPresent                                     : False
CsInfraredSupported                                     : False
CsInitialLoadInfo                                       :
CsInstallDate                                           :
CsKeyboardPasswordStatus                                : Unknown
CsLastLoadInfo                                          :
CsManufacturer                                          : Dell Inc.
CsModel                                                 : XPS 13 9350
CsName                                                  : CLIENT
CsNetworkAdapters                                       : {WiFi, Bluetooth-Netzwerkverbindung}
CsNetworkServerModeEnabled                              : True
CsNumberOfLogicalProcessors                             : 4
CsNumberOfProcessors                                    : 1
CsProcessors                                            : {Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz}
CsOEMStringArray                                        : {Dell System, 1[0704], 3[1.0], 12[www.dell.com]...}
CsPartOfDomain                                          : False
CsPauseAfterReset                                       : -1
CsPCSystemType                                          : Mobile
CsPCSystemTypeEx                                        : Mobile
CsPowerManagementCapabilities                           :
CsPowerManagementSupported                              :
CsPowerOnPasswordStatus                                 : Unknown
CsPowerState                                            : Unknown
CsPowerSupplyState                                      : Safe
CsPrimaryOwnerContact                                   :
CsPrimaryOwnerName                                      : user@company.de
CsResetCapability                                       : Other
CsResetCount                                            : -1
CsResetLimit                                            : -1
CsRoles                                                 : {LM_Workstation, LM_Server, NT, Potential_Browser...}
CsStatus                                                : OK
CsSupportContactDescription                             :
CsSystemFamily                                          :
CsSystemSKUNumber                                       : 0704
CsSystemType                                            : x64-based PC
CsThermalState                                          : Safe
CsTotalPhysicalMemory                                   : 17045016576
CsPhyicallyInstalledMemory                              : 16777216
CsUserName                                              : CLIENT12\TEST
CsWakeUpType                                            : PowerSwitch
CsWorkgroup                                             : WORKGROUP
OsName                                                  : Microsoft Windows 10 Pro
OsType                                                  : WINNT
OsOperatingSystemSKU                                    : 48
OsVersion                                               : 10.0.14393
OsCSDVersion                                            :
OsBuildNumber                                           : 14393
OsHotFixes                                              : {KB3176936, KB3194343, KB3199209, KB3199986...}
OsBootDevice                                            : \Device\HarddiskVolume1
OsSystemDevice                                          : \Device\HarddiskVolume3
OsSystemDirectory                                       : C:\WINDOWS\system32
OsSystemDrive                                           : C:
OsWindowsDirectory                                      : C:\WINDOWS
OsCountryCode                                           : 1
OsCurrentTimeZone                                       : 120
OsLocaleID                                              : 0409
OsLocale                                                : en-US
OsLocalDateTime                                         : 10/28/2016 4:11:51 PM
OsLastBootUpTime                                        : 10/19/2016 7:48:03 AM
OsUptime                                                : 9.08:23:47.7627676
OsBuildType                                             : Multiprocessor Free
OsCodeSet                                               : 1252
OsDataExecutionPreventionAvailable                      : True
OsDataExecutionPrevention32BitApplications              : True
OsDataExecutionPreventionDrivers                        : True
OsDataExecutionPreventionSupportPolicy                  : OptIn
OsDebug                                                 : False
OsDistributed                                           : False
OsEncryptionLevel                                       : 256
OsForegroundApplicationBoost                            : Maximum
OsTotalVisibleMemorySize                                : 16645524
OsFreePhysicalMemory                                    : 9128212
OsTotalVirtualMemorySize                                : 19135892
OsFreeVirtualMemory                                     : 8607696
OsInUseVirtualMemory                                    : 10528196
OsTotalSwapSpaceSize                                    :
OsSizeStoredInPagingFiles                               : 2490368
OsFreeSpaceInPagingFiles                                : 2442596
OsPagingFiles                                           : {C:\pagefile.sys}
OsHardwareAbstractionLayer                              : 10.0.14393.206
OsInstallDate                                           : 8/17/2016 3:40:27 PM
OsManufacturer                                          : Microsoft Corporation
OsMaxNumberOfProcesses                                  : 4294967295
OsMaxProcessMemorySize                                  : 137438953344
OsMuiLanguages                                          : {de-DE, en-US}
OsNumberOfLicensedUsers                                 :
OsNumberOfProcesses                                     : 157
OsNumberOfUsers                                         : 2
OsOrganization                                          :
OsArchitecture                                          : 64-bit
OsLanguage                                              : de-DE
OsProductSuites                                         : {TerminalServicesSingleSession}
OsOtherTypeDescription                                  :
OsPAEEnabled                                            :
OsPortableOperatingSystem                               : False
OsPrimary                                               : True
OsProductType                                           : WorkStation
OsRegisteredUser                                        : test@company.com
OsSerialNumber                                          : 00330-50021-50665-AAOEM
OsServicePackMajorVersion                               : 0
OsServicePackMinorVersion                               : 0
OsStatus                                                : OK
OsSuites                                                : {TerminalServices, TerminalServicesSingleSession}
OsServerLevel                                           :
KeyboardLayout                                          : de-DE
TimeZone                                                : (UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna
LogonServer                                             : \\CLIENT
PowerPlatformRole                                       : Mobile
HyperVisorPresent                                       : False
HyperVRequirementDataExecutionPreventionAvailable       : True
HyperVRequirementSecondLevelAddressTranslation          : True
HyperVRequirementVirtualizationFirmwareEnabled          : True
HyperVRequirementVMMonitorModeExtensions                : True
DeviceGuardSmartStatus                                  : Off
DeviceGuardRequiredSecurityProperties                   :
DeviceGuardAvailableSecurityProperties                  :
DeviceGuardSecurityServicesConfigured                   :
DeviceGuardSecurityServicesRunning                      :
DeviceGuardCodeIntegrityPolicyEnforcementStatus         :
DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus :

PowerShell 技能连载 - 本地帐户的内置支持

从 PowerShell 5.1 开始,终于内置支持了本地用户账户。PowerShell 5.1 现在支持 Windows 10 和 Windows Server 2016:

PS C:\> Get-Command -Module *LocalAccounts | Select-Object -ExpandProperty Name

Add-LocalGroupMember
Disable-LocalUser
Enable-LocalUser
Get-LocalGroup
Get-LocalGroupMember
Get-LocalUser
New-LocalGroup
New-LocalUser
Remove-LocalGroup
Remove-LocalGroupMember
Remove-LocalUser
Rename-LocalGroup
Rename-LocalUser
Set-LocalGroup
Set-LocalUser

PowerShell 技能连载 - 使用 Add-Member 时请注意!

Add-Member 常用来创建自定义对象,例如:

1
2
3
4
5
$o = New-Object -TypeName PSObject
$o | Add-Member -MemberType NoteProperty -Name Notes -Value 'Something'
$o | Add-Member -MemberType NoteProperty -Name Date -Value (Get-Date)

$o

这可以工作,结果类似这样:

PS C:\> $o

Notes     Date
-----     ----
Something 10/28/2016 3:56:53 PM

然而,这样做效率不高。因为 Add-Member 时动态地扩展现有的对象,而不是创建新的对象。以上代码可以用这种方法更容易地实现:

1
2
3
4
5
6
$o = [PSCustomObject]@{
Notes = 'Something'
Date = Get-Date
}

$o

Add-Member 可以做更多高级的事情,例如添加脚本属性和方法。请检查当您向以上对象添加动态脚本属性时发生了什么:

1
2
3
4
5
6
$o = [PSCustomObject]@{
Notes = 'Something'
Date = Get-Date
}

$o | Add-Member -MemberType ScriptProperty -Name CurrentDate -Value { Get-Date }

现在请看多次查询该对象时,它的 DateCurrentDate 属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
PS C:\> $o

Notes Date CurrentDate
----- ---- -----------
Something 10/28/2016 4:01:54 PM 10/28/2016 4:01:57 PM



PS C:\> $o

Notes Date CurrentDate
----- ---- -----------
Something 10/28/2016 4:01:54 PM 10/28/2016 4:02:00 PM



PS C:\> $o

Notes Date CurrentDate
----- ---- -----------
Something 10/28/2016 4:01:54 PM 10/28/2016 4:02:02 PM

Date 属性返回的是静态信息而CurrentDate 属性总是返回当前时间,因为它的值是一个脚本,每次查询这个属性的时候都会执行一次。