huerta
huerta

Reputation: 1

Import -csv to change givenname through power shell

Hello I am new to powershell and have successfully imported over 400 users using a csv file. I had a typo in my CSV file that caused the given name to be firstname+lastname instead of just the user's first name. I am trying to change JUST the first name of these users that are in the "TestOU" OU. I am looking at the easiest way to do this with only changing the givenname of each user as everything else is correct.

Server 2012 R2 The users are located in cn=domain users,ou=testou,dc=school,dc=local

Upvotes: 0

Views: 791

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36297

Pretty much what Alexander said to get only the users in that OU...

Get-ADUser -Filter * -SearchBase ",OU=TestOU,DC=school,DC=local" 

Then you can calculate what the GivenName should have been by removing the surname from it, and trimming for extra trailing spaces.

Get-ADUser -Filter * -SearchBase ",OU=TestOU,DC=school,DC=local" | ForEach-Object { 
    $Given = $_.GivenName -replace $_.SurName
    $_ | Set-ADUser -GiveName $Given.Trim()
}

Edit: However unlikely it seems to me, I should warn you that if a user has identical first and last names, and the GivenName field only has their first name it will leave the field blank. So if their name is "Andrew Andrew", where 'Andrew' is both their first and last name, and the GivenName field is currently set to 'Andrew' it will erase it. I suppose you could add some logic in there to avoid that...

If(!([string]::IsNullOrEmpty($Given.Trim()))){
    $_ | Set-ADUser -GivenName $Given.Trim()
}

That should do it I suppose, to avoid blank GivenName fields.

Edit2: You know, if you still have your CSV you could do this easier. Fix your GivenName column. Remove all columns except that one and the SAMAccountName column. Then you should be able to just do:

Import-CSV 'C:\Path\To\File.csv' | ForEach{ Set-ADUser $_.samaccountname -GivenName $_.GivenName }

Upvotes: 2

Related Questions