问题
I have a PS object and couldnt figure out a way to append values to my object.
$object = New-Object PSObject
Add-Member -InputObject $object -MemberType NoteProperty -Name Col1 -Value ""
Add-Member -InputObject $object -MemberType NoteProperty -Name Col2 -Value ""
Add-Member -InputObject $object -MemberType NoteProperty -Name Type -Value ""
1..10 |ForEach{
$src=$_
11..20 | ForEach{
$dst = $_
$object.Col1=$src
$object.Col2=$dst
$object.Type="New"
}
}
I want my result like
col1 col2 Type ---- ---- ---- 1 11 New 1 12 New 1 13 New 1 14 New ...
回答1:
Use a PSCustomObject:
$values = 1..10 | % {
[pscustomobject]@{ col1=1; col2=10+$_; Type="New" }
}
回答2:
The output you want is a list of objects, not a single object. You generate that by creating the objects inside the loop. @Burt_Harris already showed you one way to do that (using a type accelerator [PSCustomObject]
), but of course you can also use New-Object
to the same end:
$list = 1..10 | ForEach-Object {
$src = $_
11..20 | ForEach-Object {
$prop = @{
Col1 = $src
Col2 = $_
Type = 'New'
}
New-Object -Type PSObject -Property $prop
}
}
Create the property hashtable as an ordered hashtable if you want the properties to appear in a particular order in the output (PowerShell v3 and newer only):
$prop = [ordered]@{
Col1 = $src
Col2 = $_
Type = 'New'
}
The list of objects can be captured by assigning the pipeline output to a variable ($list = ...
).
来源:https://stackoverflow.com/questions/39520329/append-values-to-powershell-object