1

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?

1 Answer 1

3

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

1 Comment

Exactly as suspected - I tried $a.PropertyCount() which returned dozens of properties followed by 0 after new-object.

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.