1

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
...

2 Answers 2

2

Use a PSCustomObject:

$values = 1..10 | % { 
   [pscustomobject]@{ col1=1; col2=10+$_; Type="New" }
   }
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks, how do i save that to an object and use it some where in my script.I tired saving it an object, but it saved only last element.
PSOjbect or PSCustomObject doesn't make a difference (unless you want to use a type accelerator). The point is to create (and output) new objects inside the loop. The list can be captured by assigning the pipeline output to a variable: $list = 1..10 | % {...}
I've updated the example to save into variable $values. I get different results @AnsgarWiechers, try it yourself replacing pscustomobject with psobject.
You're using a type accelerator, so yes, you're getting different results. Use New-Object and the results will be the same.
@AnsgarWiechers, yes but try this: New-Object -Type PSObject | GM. It returns a PSCustomObject even though you ask for a PSObject. Special cases abound in this area.
|
1

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 = ...).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.