问题
I have a powershell script that builds active directory users based on CSV file. It has the attributes defined like this:
-GivenName $_.FirstName `
-Surname $_.LastName `
-SamAccountName $_.UserName `
I want to add the DisplayName attribute to combine $.FirstName and $.LastName with a space in the between. I tried:
-DisplayName $_.FirstName + " " + $_.LastName `
But the above doesn't work, it gives an error.
Can anyone kindly suggest how I can define the DisplayName attribute with the firstname and lastname from the CSV data?
Thanks
回答1:
When PowerShell looks at arguments passed to a command, each individual token is interpreted as a separate input argument.
Wrap the string concatenation in a sub-expression ($()
) to pass it as a single string:
Set-ADUser ... -DisplayName $($_.FirstName + " " + $_.LastName)
or use an expandable string:
Set-ADUser ... -DisplayName "$($_.FirstName) $($_.LastName)"
As Lee_Dailey notes, you might want to use a technique called "splatting" to organize your parameter arguments instead of splitting them over multiple lines:
Import-Csv users.csv |ForEach-Object {
$parameterArgs = @{
Name = $_.Name
SamAccountName = $_.UserName
GivenName = $_.FirstName
Surname = $_.LastName
DisplayName = $_.FirstName,$_.LastName -join ' '
}
# pass our parameter arguments by "@splatting"
New-ADUser @parameterArgs
}
来源:https://stackoverflow.com/questions/60714158/powershell-active-directory-displayname