Reputation: 31
I have a script (thanks in largely to this site) that takes names of people from a text file and splits them into FullName, FirstName, LastName and FirstLetter.
I now plan on importing these into AD and largely, I know what I am doing.
However, I am struggling with the following section
New-ADUser -Name
I would like to do something like this
$result.ForEach({
New-ADUser -Name $_.FirstName + $_.LastName -GivenName $_.FirstName -Surname
$_.LastName -AccountPassword
(ConvertTo-SecureString -AsPlainText "APassword!" -Force)
-PasswordNeverExpires $True -UserPrincipalName
"[email protected]"
-SamAccountName "$_.FirstLetter $_.LastName"
-Path 'OU=Users,OU=London,OU=Sites,DC=MyCompany,DC=local'
})
This returns a error stating 'The name provided is not a properly formed account name'. Now I presume this is because, if I do this
$result.FirstName + $result.LastName
It returns the 3 first names and the 3 last names on seperate lines, so I would presume it is trying to name each person with a name on two seperate lines like
So how would I make the result display on one line, presuming this is the issue?
Also, if there are better ways of doing the AD Creation then please advise, I am still learning!
Upvotes: 0
Views: 118
Reputation: 8889
Enclose the two variables in parentheses to get the results of the addition just like you did in the ConvertTo-SecureString
part:
$result.ForEach({
New-ADUser -Name ($_.FirstName + "" + $_.LastName) -GivenName $_.FirstName -Surname
$_.LastName -AccountPassword
(ConvertTo-SecureString -AsPlainText "APassword!" -Force)
-PasswordNeverExpires $True -UserPrincipalName
"[email protected]"
-SamAccountName "$_.FirstLetter $_.LastName"
-Path 'OU=Users,OU=London,OU=Sites,DC=MyCompany,DC=local'
})
Now, as you asked for better ways, see few possibilities including Splatting parameters and string.format (-f)
Also notice the differents between the string formatting in the Name
and SamAccountName
Parameters:
foreach ($user in $result)
{
$Params = @{
Name = "$($user.FirstName) $($user.LastName)"
GivenName = $user.FirstName
Surname = $user.LastName
AccountPassword = (ConvertTo-SecureString -AsPlainText "APassword!" -Force)
PasswordNeverExpires = $true
UserPrincipalName = "{0}{1}@vennershipley.co.uk" -f $user.FirstName.Chars(0),$_.Lastname
SamAccountName = "{0}{1}" -f $user.FirstName.Chars(0),$_.Lastname
Path = 'OU=Users,OU=London,OU=Sites,DC=MyCompany,DC=local'
}
New-ADUser @Params
}
One more thing: to check everything is good just before executing this in production, i suggest you to add the -WhatIf
parameter to the New-ADUser
cmdlet, it will demonstrate the operation but will not run it
Upvotes: 2