我创建了一个小脚本,用于接受用户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
答案 0 :(得分:2)
看起来当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"}
答案 1 :(得分:2)
使用[PSCustomObject]
创建PowerShell知道如何呈现为字符串的类型:
$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"
}
$personHash[$userID] = [pscustomobject]@{ID=$userID; First=$firstname; Last=$lastname}
$personHash