Powershell 哈希表问题

标签 powershell

我创建了一个小脚本来接受用户 ID、名字、姓氏,然后将该数据添加到哈希表中。我遇到的问题是当我显示我的哈希表时说用户的值是 System.Object。我做错了什么?

$personHash = @{}
$userID=""
$firstname=""  
$lastname=""


    While([string]::IsNullOrWhiteSpace($userID))
    {
        $userID = Read-Host "Enter ID"
    }

    While([string]::IsNullOrWhiteSpace($firstname))
    {
        $firstname = Read-Host "Enter First Name"
    }


    While([string]::IsNullOrWhiteSpace($lastname))
    {
        $lastname = Read-Host "Enter Last Name"
    }


$user = New-Object System.Object
$user | Add-Member -type NoteProperty -Name ID -value $userID
$user | Add-Member -type NoteProperty -Name First -value $firstname
$user | Add-Member -type NoteProperty -Name Last -Value $lastname
$personHash.Add($user.ID,$user)

$personHash

最佳答案

看起来当 PowerShell 显示哈希表的内容时,它只是对表中的对象调用 ToString。它不会像通常那样使用 DefaultDisplayPropertySet 对它们进行格式化。

一种替代方法是像这样使用 PSCustomObject 而不是 System.Object:

$user = New-Object PSCustomObject -Property @{ ID = $userID; First = $firstname; Last = $lastname }
$personHash.Add($user.ID, $user)

然后显示会是这样的:

Name         Value  
----         -----  
1            @{ID=1;First="Mike";Last="Z"}

关于Powershell 哈希表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27462405/

相关文章:

rest - 使用 cURL 的 Powershell 2.0 POST 请求

powershell - 属性System.Boolean IsReadOnly = False

powershell - 在PowerShell中选择带有变量的属性或参数

performance - 加快用于 Windows 注册表搜索的 PowerShell 脚本(目前为 30 分钟)

powershell - 使用Powershell获取HDD序列号

function - 从脚本 block 动态创建 PowerShell 脚本 block

powershell - Powershell意外 token

powershell - 使用Powershell管道通过调用函数向对象集合添加动态属性

powershell - PowerShell日期时间转换问题

powershell - 将函数与 ForEach-Object 一起使用