PowerShell 技能连载 - 在同一台机器上运行 32 位代码
如果您需要在 64 位脚本中运行 32 位 PowerShell 代码,假设您是管理员,并且使用远程操作功能,您可以远程操作您的系统:
1 | $code = { |
这将在 32 位环境中运行 $code
中的脚本块。该指针返回的 size 是 4,这是 32 位的证据。当您直接运行脚本块,返回的是 8 字节(64 比特)。
如果您需要在 64 位脚本中运行 32 位 PowerShell 代码,假设您是管理员,并且使用远程操作功能,您可以远程操作您的系统:
1 | $code = { |
这将在 32 位环境中运行 $code
中的脚本块。该指针返回的 size 是 4,这是 32 位的证据。当您直接运行脚本块,返回的是 8 字节(64 比特)。
曾几何时,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 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
Add-Member
常用来创建自定义对象,例如:
1 | $o = New-Object -TypeName PSObject |
这可以工作,结果类似这样:
PS C:\> $o
Notes Date
----- ----
Something 10/28/2016 3:56:53 PM
然而,这样做效率不高。因为 Add-Member
时动态地扩展现有的对象,而不是创建新的对象。以上代码可以用这种方法更容易地实现:
1 | $o = [PSCustomObject]@{ |
Add-Member
可以做更多高级的事情,例如添加脚本属性和方法。请检查当您向以上对象添加动态脚本属性时发生了什么:
1 | $o = [PSCustomObject]@{ |
现在请看多次查询该对象时,它的 Date
和 CurrentDate
属性
1 | PS C:\> $o |
Date
属性返回的是静态信息而CurrentDate
属性总是返回当前时间,因为它的值是一个脚本,每次查询这个属性的时候都会执行一次。
在前一个技能中我们介绍了如何快速用 PSCustomObject
创建一个新对象:
$o = [PSCustomObject]@{
Date = Get-Date
BIOS = Get-WmiObject -Class Win32_BIOS
Computer = $env:COMPUTERNAME
OS = [Environment]::OSVersion
Remark = 'Some remark'
}
实际中,[PSCustomObject]
并不是一个类型,并且也不是在转型一个哈希表。这个场景背后实际发生的是两个步骤的组合,您也可以分别执行这两个步骤:
1 | #requires -Version 3.0 |
由于这段代码用到了 PowerShell 3.0 引入的排序的哈希表,所以无法在 PowerShell 2.0 中使用相同的做法。要支持 PowerShell 2.0 ,请用无序的(传统的)哈希表代替:
1 | #requires -Version 2.0 |
要将一系列信息打包起来的最好方法就是将它们存储在自定义对象中。最简单最快捷的方法就是用 PSCustomObject
:
1 | #requires -Version 3.0 |
在大括号内,将一系列信息(或命令执行结果)存储在键中。这将创建一个将包含一系列信息的对象:
PS C:\> $o
Date : 10/28/2016 3:47:27 PM
BIOS : \DESKTOP-7AAMJLF\root\cimv2:Win32_BIOS.Name=”1.4.4”,SoftwareElementID=”1.4.4”,SoftwareElementState=3,TargetOpera
tingSystem=0,Version=”DELL - 1072009”
Computer : DESKTOP-7AAMJLF
OS : Microsoft Windows NT 10.0.14393.0
Remark : Some remark
PS C:> $o.Remark
Some remark
PS C:\> $o.OS
Platform ServicePack Version VersionString
-------- ----------- ------- -------------
Win32NT 10.0.14393.0 Microsoft Windows NT 10.0.14393.0
PS C:> $o.OS.VersionString
Microsoft Windows NT 10.0.14393.0
PS C:\>
PowerShell 将您的所有交互命令行输入“记录”到它的命令行历史中,而 Get-History
负责显示它们。如果您运行了一段时间 PowerShell 并且觉得运行的效果不错,那么可以用以下脚本将所有的交互命令从命令行历史中复制到剪贴板中。接下来您可以将它们粘贴到 PowerShell ISE 中,并使之成为一个脚本:
1 | # define how old your commands may be at most to be included |
在 www.powershellgallery.com ,Microsoft 发布了一个公开的脚本和模块的仓库。您可以在这里和其他人交流 PowerShell 代码(请见网站)。
要使用这个仓库,您需要 PowerShell 5 或者手动安装 PowerShellGet 模块(在 powershellgallery.com 可以下载到)。接下来您可以使用诸如 Find/Save/Install/Update/Remove-Script/Module 等 cmdlet。
目前缺乏的是一个查看模块当前最新版本号的方法。以下是解决方案:
1 | function Get-PublishedModuleVersion($Name) |
当您运行 Get-PublishedModuleVersion
并传入发布的模块名,执行结果类似如下:
PS C:\> Get-PublishedModuleVersion -Name ISESteroids
Major Minor Build Revision
----- ----- ----- --------
2 6 3 25
这个操作非常非常快,而且可以用来检测已安装的模块,看它们是否是最新版本。
Test-Path
在测试一个文件或文件夹是否存在时十分有用,它可以用在任何 PowerShell 驱动器上。所以它也可以测试一个变量、一个函数,或一个证书是否存在(举个例子)。
In recent PowerShell versions, Test-Path can now differentiate between containers (i.e. folders) and leafs (i.e. files), too:
在近期的 PowerShell 版本中,Test-Path
还可以区分容器(例如文件夹)和叶子(例如文件):
1 | $path = 'c:\windows\explorer.exe' |
在 PowerShell 5.0 中似乎有个 bug,限制了内置帮助窗口的作用。当您以 -ShowWindow
参数运行 Get-Help
命令时,该窗口只显示该 cmdlet 的语法和例子。许多额外信息并没有显示出来。
要获得某个 cmdlet 支持的参数的详细信息,请直接请求该信息。以下代码将解释 Get-Date
中的 -Format
参数是做什么的:
PS C:\> Get-Help -Name Get-Date -Parameter Format
-Format []
Displays the date and time in the Microsoft .NET Framework format indicated by the
format specifier. Enter a format specifier. For a list of available format
specifiers, see DateTimeFormatInfo Class
(http://msdn.microsoft.com/library/system.globalization.datetimeformatinfo.aspx)
in MSDN.
When you use the Format parameter, Windows PowerShell gets only the properties of
the DateTime object that it needs to display the date in the format that you
specify. As a result, some of the properties and methods of DateTime objects might
not be available.
Starting in Windows PowerShell 5.0, you can use the following additional formats
as values for the Format parameter.
-- FileDate. A file or path-friendly representation of the current date in local
time. It is in the form of yyyymmdd ( using 4 digits, 2 digits, and 2 digits). An
example of results when you use this format is 20150302.
-- FileDateUniversal. A file or path-friendly representation of the current date
in universal time. It is in the form of yyyymmdd + 'Z' (using 4 digits, 2 digits,
and 2 digits). An example of results when you use this format is 20150302Z.
-- FileDateTime. A file or path-friendly representation of the current date and
time in local time, in 24-hour format. It is in the form of yyyymmdd + 'T' +
hhmmssmsms, where msms is a four-character representation of milliseconds. An
example of results when you use this format is 20150302T1240514987.
-- FileDateTimeUniversal. A file or path-friendly representation of the current
date and time in universal time, in 24-hour format. It is in the form of yyyymmdd
+ 'T' + hhmmssmsms, where msms is a four-character representation of milliseconds,
+ 'Z'. An example of results when you use this format is 20150302T0840539947Z.
Required? false
Position? named
Default value none
Accept pipeline input? false
Accept wildcard characters? false
通过这些信息,您现在可以知道如何格式化日期和时间:
1 | $date = Read-Host -Prompt 'Enter a date' |