自定义PSObject中的额外空间

时间:2015-05-08 20:35:55

标签: powershell

我正在构建自定义PSObject阵列,但我注意到很多额外的空间正在插入,没有明显的原因。例如:

PS> $user = @()
PS> $user += New-Object PSObject -Property @{"Name" = "John Smith"}
PS> $user += New-Object PSObject -Property @{"Age" = "18"}
PS> $user += New-Object PSObject -Property @{"City of birth" = "New York"}
PS> $user += New-Object PSObject -Property @{"Pet" = "none"}
PS> "[$($user.Name)]"
[John Smith   ]
PS> "[$($user.Pet)]"
[   none]

似乎我添加的键/值对越多,这些值的空间就越多。任何想法为什么会这样?

2 个答案:

答案 0 :(得分:2)

$user是一个数组,因此$user.Name的行为是获取所有条目的Name属性。由于它被放入一个字符串中,因此值通过空格连接在一起。因此,每次向$user添加条目时,都会在所有属性的某处添加一个额外的空格。

我不确定您是否将$user定义为数组。构建所有属性的哈希表并使用初始化$user作为PSObject更有意义:

$props = @{ "Name" = "John Smith"; "Age" = "18"; "City of birth" = "New York"; "Pet" = "none"}
$user = New-Object PSObject -Property $props

或者如果您需要动态构建一些属性:

$props = @{ "Name" = "John Smith"; "Age" = "18"; "City of birth" = "New York"; "Pet" = "none"}
if ($myCondition) 
{
    $props.PropertyA = "A"
}
else
{
    $props.PropertyB = "B"
}
$user = New-Object PSObject -Property $props

或者如果您是从database it would probably look more like this

中阅读它们
while($reader.Read()) {
     $props = @{}
     for($i = 0; $i -lt $reader.FieldCount; $i+=1) {
        $name = $reader.GetName($i)
        $value = $reader.item($i)
        $props.Add($name, $value)   
     }
     $obj = new-object PSObject -Property $props
     Write-Output $obj
}

答案 1 :(得分:0)

感谢@ mike-z提供关于Add-Member的评论。原来这个代码做了我想要的:

PS> $user = New-Object PSObject
PS> $user | Add-Member -NotePropertyName "Name" -NotePropertyValue "John Smith"
PS> $user | Add-Member -NotePropertyName "Age" -NotePropertyValue "18"
PS> $user | Add-Member -NotePropertyName "City of birth" -NotePropertyValue "New York"
PS> $user | Add-Member -NotePropertyName "Pet" -NotePropertyValue "none"