0

Trying to build a custom object inside a For-EachObject loop.

Here is the code

$infouser =  New-Object -TypeName psobject 

(Get-ChildItem -Path "\\$poste\C$\Users").Name | ForEach-Object {

$nomcomplet += Get-ADUser -Identity $_ | select-object -ExpandProperty userprincipalname 

Add-Member -InputObject $infouser -Name "Code" -Value $_ -MemberType NoteProperty
Add-Member -InputObject $infouser -Name "Nom complet" -Value $nomcomplet -MemberType NoteProperty

}


$infouser | Out-GridView

What i'm trying to achieve is a custom object containing the usernames in C:\USERS along with their equivalent full e-mail adress from the AD.

What I have works partially, it displays the first one it can add, but it doesn't "append" the others : enter image description here

Giving the error : "Add-Member : Cannot add a member with the name...because a member with that name already exists. If you want to overwrite the member anyway, use the Force parameter to overwrite it."

I don't want to overwrite, I want to append it to the object so the final object contains all usernames and all adresses.

What am I doing wrong here? Thanks

1
  • 2
    You should use a array of custom objects Commented Oct 3, 2018 at 15:43

1 Answer 1

1

You need to create an array of psobjects, not a single psobject. You're creating a single object and re-adding the properties X times.

This implicitly creates an array and adds a new psobject for each loop.

$infouser = (Get-ChildItem -Path "\\$poste\C$\Users").Name | ForEach-Object {
    [pscustomobject]@{
        'Code' = $_
        'Nom Complet' = $(Get-ADUser -Identity $_ | select-object -ExpandProperty userprincipalname )
    }
}

$infouser | Out-GridView
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh great. I knew my logic was wrong, thanks a lot for your help.
Love the use of $() instead of additing results to a variable, much more concise

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.