Home > OS >  Adding values from two arrays into a PSCustomObject
Adding values from two arrays into a PSCustomObject

Time:01-25

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?

CodePudding user response:

Instead of using =, simply assign all the output from the loop to a variable (also note that you'll probably want to index into $users rather than the synthetic collection(s) you get from $users.name etc. - otherwise it'll break if any property contains multiple values):

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

CodePudding user response:

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]
    }    
}
  •  Tags:  
  • Related