'Adding values from two arrays into a PSCustomObject

I am trying to combine values from two arrays into a table using a PSCustomObject.

One array has the passwords and one array has the users.

When I try to combine them in to a PSCustomObject array it only list the last value in the array, not a list.

I have tried a few different versions:

for ($i = 0; $i -lt $users.Length; $i++) {$myObject = [PSCustomObject] @{name = $users.name[$i]; User = $users.samaccountname[$i]; Mail = $users.mail[$i]; Password = $passwords[$i]}}

and

foreach ($psw in $passwords) {$users | % {$myObject = [PSCustomObject] @{name = $PSItem.name; User = $PSItem.samaccountname; Mail = $PSItem.mail; Password = $psw}}}

When I try to use += on $myobject it gives the error:

Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.

Any ideas what I am doing wrong?



Solution 1:[1]

The error you get when using += on $myobject is caused because $myobject is of a custom type (without the 'op_Addition' method implemented).

You can use an object with this method implemented, for example ArrayList, like that:

$myObject = New-Object -TypeName "System.Collections.ArrayList"

for ($i = 0; $i -lt $users.Length; $i++) {
    $myObject += [PSCustomObject] @{
        Name = $users[$i].name
        User = $users[$i].samaccountname 
        Mail = $users[$i].mail
        Password = $passwords[$i]
    }    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WiktorM