Powershell 没有 return 哈希表中的键值

Powershell doesn't return key value in 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

谁能解释我做错了什么?我是 Powershell 的初学者,我不明白为什么它 returns 按键为空值?

Get-CimInstance Win32_Process returns ProcessId 属性 作为类型 System.UInt32。您需要将键检索值转换为该类型或将 ProcessId 值转换为 System.Int32。原因是默认情况下 shell 将未加引号或未转换的整数解释为 System.Int32,前提是该数字小于或等于 [int32]::maxvalueSystem.Int64 否则。

在你的情况下,如果你不介意使用 Uint32:

,你可以简单地使用下面的语法
$hashx[[uint32]5164]

就个人而言,我会将 ProcessId 值转换为 System.Int32(使用加速器 [int]),然后将其添加到散列 table:

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