简体   繁体   中英

Append 2 pscustomobjects into 1

在此处输入图像描述

I am new to powershell. I have 2 pscustomobjects in powershell script. I want to bring them together as one and output into csv.

The problem is there is no key column to match in both, just want to append them together. I was able to use the following code but it does not show the data correctly. Any Suggestions? (sample attached)

$result=[pscustomobject]($a+$b)

It seems what you're looking to do is merge the properties from both objects into one.

You can access the properties and property values of an object via the intrinsic member PSObject , in this case you would need to enumerate all properties from both objects ( $a and $b ) and put them together into an ordered dictionary and lastly cast [pscustomobject] to it to get a new merged object as a result. This function can simplify that process for you.

function Merge-PSCustomObject {
    param(
        [Parameter(Mandatory)]
        [Object] $LeftObject,

        [Parameter(Mandatory)]
        [Object] $RigthObject
    )

    end {
        $result = [ordered]@{}
        foreach($property in @($LeftObject.PSObject.Properties; $RigthObject.PSObject.Properties)) {
            $result[$property.Name] = $property.Value
        }
        [pscustomobject] $result
    }
}

$a = [pscustomobject]@{ foo = 'hello' }
$b = [pscustomobject]@{ bar = 'world'; baz = 123 }

Merge-PSCustomObject -LeftObject $a -RigthObject $b

If you have an array of objects in both sides, assuming both arrays have the same count of objects , you can use a for loop to merge each object in both arrays, for example:

$a = [pscustomobject]@{ foo = 'hello' }
$b = [pscustomobject]@{ bar = 'world'; baz = 123 }

$arr1 = 0..3 | ForEach-Object { $a }
$arr2 = 0..3 | ForEach-Object { $b }

$result = for($i = 0; $i -lt $arr1.Count; $i++) {
    Merge-PSCustomObject $arr1[$i] $arr2[$i]
}

See if following works:

for($i = 0; $i -lt $a.Count; $i++)
{
   $a[$i] | Add-Member -NotePropertyName Sample3 -NotePropertyValue $b[$i].Sample3
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM