Fazer87
Fazer87

Reputation: 1242

Copy AD User with PowerShell

I have been shown the following example in a training course which I believe to be wrong.

The code is supposed to copy an Active Directory User in PowerShell:

$userInstance = Get-ADUser -Identity "kmill"

$userInstance = New-Object Microsoft.ActiveDirectory.Management.ADUser

$userInstance.DisplayName = "Peter Piper"

New-ADUser -SAMAccountName "ppiper" -Instance $userInstance

It is my understnading that we get "Kmill"'s user account as an object and store it in a variable in Line 1.

It is also my understanding that in Line 2 - we completely Overwrite that variable and essentialy wipe all data obtained in line 1 (and therefore wouldn't copy an existing user)

Am I wrong here?

Upvotes: 1

Views: 7661

Answers (1)

vonPryz
vonPryz

Reputation: 24071

Your reasoning is correct, there is a mistake in the example. You can check this easily enough by printing the objects. No user creation is needed. Like so,

PS C:\> $u = Get-ADUser -identity someUser
PS C:\> $u # Print the variable contents on console
DistinguishedName : CN=someuser...
Enabled: True
...
PS C:\> $u = New-Object Microsoft.ActiveDirectory.Management.ADUser
PS C:\> $u # Print again, all the properties are empty
GivenName          :
Surname            :
UserPrincipalName  :
PS C:\> 

Technet has a sample that uses the -Identity to pass existing user's settings as template.

PS C:\> $userInstance = Get-ADUser -Identity "saraDavis"
PS C:\> New-ADUser -SAMAccountName "ellenAdams" -Instance $userInstance -DisplayName "EllenAdams"

Upvotes: 3

Related Questions