1

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?

2 Answers 2

2

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]
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

0

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]
    }    
}

1 Comment

You don't add elements to an ArrayList using +=.

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.