Copy multi-valued Active Directory attributes from one user to another with PowerShell

Doctor Scripto

Dr Scripto

Summary: Using -Replace parameter with Set-ADUser to copy Active Directory multi-valued attributes

Q: Hey, Doctor Scripto!

We are in the middle of an Active Directory migration and need to copy the multi-valued attribute “ProxyAddresses” from old user accounts to new ones. Can you do with a few lines of code?

—ND

A: Hello ND,

Hello everyone, your good friend Doctor Scripto is here with Walid, one of our PFEs who really likes mixing PowerShell with Active Directory. Walid, what do you think of this one?

Well, Doctor Scripto, it makes a lot of sense to try and automate this type of tasks. Who likes to manually copy information from one place to another for a whole night?

The Active Directory module for PowerShell has a command called Set-ADUser, we can use the -Replace parameter to provide new values of any attribute, like ProxyAddresses for example. The -Replace parameter takes a hashtable, so we can use it to enter several attributes at once. See example below,

This will replace what ever value in the Title and Description attributes with the information above.

Now, when it comes to multi-valued attributes, we can use the -Replace, but fort the value, we need to provide an array. See this example,

Here we provided an array of strings. This is how it looks in AD,

Now to our main task, copying from one user to the another. The first step would be to get the value from the old user,

However, if we look at the object type of the extracted data, it is a collection, not an array. So we cannot directly use it.

One trick PowerShell has is its ability to cast a specific type, we can use this to quickly convert the ProxyAddresses into an Array using [Array] before the variable name,

Now we can use it to copy into the new user,

To sum it up, if we want to this for many users quickly we can use a CSV with a list of old and new users,

OldSamAccountNameNewSamAccountName
OldUser1NewUser1
OldUser2NewUser2

 

Then use PowerShell to automate the whole process,

That’s it, 4 lines. Hope this saves you some time ND.

So that is all there is to copying multi-valued attributes in Active Directory.  Pop by next week as we put on our detective hats to uncover a cool puzzle in Azure.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Forum. See you tomorrow. Until then, peace.

Your good friend, Doctor Scripto

PowerShell, Doctor Scripto, Active Directory, Walid Moselhy

 

Doctor Scripto
Dr Scripto

Scripter, PowerShell, vbScript, BAT, CMD

Follow Dr Scripto   

0 comments

    Leave a comment