Append values to Powershell object

本小妞迷上赌 提交于 2019-12-25 07:58:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!