Powershell Active Directory DisplayName

我怕爱的太早我们不能终老 提交于 2021-02-04 21:38:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!