Search code examples
powershellhashtable

How do I add a custom property to "Get-ADUser"?


I'm trying to Output information I pull from AD with Get-ADUser which is fairly straight forward, however, I am trying to add the primarysmtp address from Get-Mailbox into that array and am running into a world of problems.

Basically I have:

$newuser = Get-ADUser $Username -properties Name, DisplayName, GivenName, Surname

I wish to add a custom property to $newuser just for the output, not to the actual ADUser.

$EXmail = (Get-Mailbox $Username).PrimarySmtpAddress

How can I add $EXmail to $newuser? Would like it to just add Email : $EXMail as a property somehow..

Tried $newuser | Add-member, no luck. I tried $newuser.GetEnumerator() and adding to that, no luck. I'm hoping there is a way to do this with GetEnumerator() and just add a Key/Value as working that into my script would be the easiest.

Any help would be greatly appreciated thank you!


Solution

  • Add-Member should work for this but you need the -Force switch since there is a conflict with Email as a property name.

    $newuser | Add-Member -MemberType Noteproperty -Name "Email" -Value $EXmail -Force
    

    An alternative is to use Select-Object and you won't have to change $newuser object at all.

    $newuser | Select-Object Name,DisplayName,GivenName,Surname,@{n="Email";e={$EXMail}}