Est*_*tet 0 powershell null hashtable
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
Run Code Online (Sandbox Code Playgroud)
谁能解释一下我做错了什么?我是 powershell 的初学者,我不明白为什么它按键返回空值?
Get-CimInstance Win32_Process以 type返回ProcessId属性System.UInt32。您需要将密钥检索值转换为该类型或将ProcessId值转换为System.Int32. 原因是默认情况下 shell 会解释未加引号或未转换的整数,System.Int32前提是该数字小于或等于[int32]::maxvalue或System.Int64其他情况。
在您的情况下,如果您不介意使用以下语法,则可以简单地使用以下语法Uint32:
$hashx[[uint32]5164]
Run Code Online (Sandbox Code Playgroud)
就我个人而言,在将其添加到哈希表时,我会将ProcessId值转换为System.Int32(使用 Accelerator ):[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]
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您可以使用以下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
Run Code Online (Sandbox Code Playgroud)
ProcessId请注意shows type的定义uint32。
| 归档时间: |
|
| 查看次数: |
765 次 |
| 最近记录: |