问题描述
PS C:\Users\kris> $hashx=@{}
PS C:\Users\kris> $(Get-CimInstance Win32_Process | Select-Object ProcessId,Name) | ForEach-Object { $hashx[$_.ProcessId]=$_.Name }
PS C:\Users\kris> $hashx
Name Value
---- -----
1292 svchost.exe
6032 startmenuExperienceHost.exe
428 smss.exe
4736 powershell.exe
2580 svchost.exe
5628 explorer.exe
5164 taskhostw.exe
PS C:\Users\kris> $hashx['5164']
PS C:\Users\kris> $hashx.5164
PS C:\Users\kris> $hashx."5164"
PS C:\Users\kris> $hashx.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
谁能解释一下我做错了什么?我是 powershell 的初学者,我不明白为什么它会按键返回空值?
解决方法
Get-CimInstance Win32_Process
以 ProcessId
类型返回 System.UInt32
属性。您需要将密钥检索值转换为该类型或将 ProcessId
值转换为 System.Int32
。原因是默认情况下,如果数字小于或等于 System.Int32
或 [int32]::maxvalue
,否则 shell 会将未加引号或未转换的整数解释为 System.Int64
。
就您而言,如果您不介意使用 Uint32
,则可以简单地使用以下语法:
$hashx[[uint32]5164]
就个人而言,当将 ProcessId
值添加到哈希表时,我会将其转换为 System.Int32
(使用加速键 [int]
):
Get-CimInstance Win32_Process |
Select-Object ProcessId,Name | ForEach-Object {
$hashx[[int]$_.ProcessId] = $_.Name
}
# Now the keys can be accessed using Int32 numbers
$hashx[5164]
顺便说一句,您可以使用 Get-Member
命令自行发现属性类型:
Get-CimInstance win32_Process |
Select -First 1 -Property ProcessId | Get-Member
TypeName: Selected.Microsoft.Management.Infrastructure.CimInstance
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
ProcessId NoteProperty uint32 ProcessId=0
注意 ProcessId
的定义显示类型 uint32
。