I tried to automate creating AD users in my lab environment and came across an interesting issue that I cannot seem to grasp. When I tried using the following code, Powershell threw "New-ADUser : The name provided is not a properly formed account name"
$Attributes = @{
Enabled = $true
ChangePasswordAtLogon = $false
Departent = "MyDepartment"
UserPrincipalNAme = "[email protected]"
City = "MySite"
DisplayName = "My display name"
EmailAddress = "[email protected]"
GivenName = "First Name"
Manager = "cbu"
PasswordNeverExpires = $true
SamAccountName = "abc123"
Surname = "Last name"
Title = "Title"
Name = "abc123"
AccountPassword = $("Thishere1234" | ConvertTo-SecureString -AsPlainText -Force)
}
New-ADUser $Attributes
The above example is close to a copy paste from some post that I found using hashtables as a way to pass the information to New-ADUser. Since this did not work, I instead tried the following:
$Attributes = [pscustomobject]@{
Enabled = $true
ChangePasswordAtLogon = $false
Departent = "MyDepartment"
UserPrincipalNAme = "[email protected]"
City = "MySite"
DisplayName = "My display name"
EmailAddress = "[email protected]"
GivenName = "First Name"
Manager = "cbu"
PasswordNeverExpires = $true
SamAccountName = "abc123"
Surname = "Last name"
Title = "Title"
Name = "abc123"
AccountPassword = $("Thishere1234" | ConvertTo-SecureString -AsPlainText -Force)
}
$Attributes | New-ADUser
This works just fine. My question is: why would the first hashtable approach not accept the name property but the second PSCustomObject does accept the exact same approach?
As a bonus question, is there any particular reason I cannot use New-ADUser $Attributes but rather I have to pipe $Attributes to New-ADUser? I was under the impression you could use the former too?