微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Powershell 不返回哈希表中的键值

如何解决Powershell 不返回哈希表中的键值

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_ProcessProcessId 类型返回 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。