Ahmed
Ahmed

Reputation: 1533

Powershell Active Directory DisplayName

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

Upvotes: 0

Views: 2981

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

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
}

Upvotes: 3

Related Questions