How to edit only the Firstname (givenName) of multiple users and import with csv

筅森魡賤 提交于 2019-12-11 16:19:01

问题


If I have a list of users where the samAccountName for all the users are all numerical Example, 745744, 745746, etc…. I was looking for a powershell script that could accomplish the following:

  1. Put an “XX” without quotes in front of the users first name/givenname
  2. Have the script import the list of users from the csv file if I have a list of all the users samAccountName.

Is having only one column in excel with the samAccountName sufficient for the csv, or do i need to also have all of the users givenName as well inside of the csv?? Example column A samAccountName, column B Firstname??

Example givenName is, JOAQUIN, I would need the first name to be XXJOAQUIN. I have about 500 users that I would have to do this for, and we are doing it manually right now, So the only thing that I need changed is adding the “XX” before the users givenNames….

Thanks everyone in advance.


回答1:


If your CSV file just contains a header with the samAccountName followed by the samAccountNames like this:

samAccountName
745744
745746

Then you can use the following piece of code, change the path to the path of the csv file with your users. This could be made shorter and use the pipeline better to make it less code, but this will work just fine.

$users = Import-Csv -Path .\users.csv 

foreach($user in $users) {
$obj = Get-ADUser -Identity $user.samAccountName
Set-ADUser -Identity $user.samAccountName -GivenName ("xx" + $obj.GivenName)
}



回答2:


If you have a CSV with samAccountName as the first column, you can do something like this.

$Users = Import-CSV "Users.csv"
Foreach($User in $Users){

$ADUser = Get-ADUser $User.samAccountName

$ADUser.GivenName = "XX$($ADUser.GivenName)"

Set-ADUser -Instance $ADUser
}

If you are searching for numerical users, you can look up in the documentation to use Get-ADUser to get all your users, and use a foreach loop to evaluate if it is numerical, and set the account.




回答3:


You can also pipe the output directly from Get-ADUser to Set-ADUser like this:

$users = Import-Csv -Path .\users.csv 
foreach($user in $users) {
  Get-ADUser -Identity $user.SamAccountName | % {Set-ADUser -Identity $_.SamAccountName -GivenName ("xx" + $_.GivenName)}
}

Another way would be:

$users = Import-Csv -Path .\users.csv 
foreach($user in $users) {
  Set-ADUser -Identity $user.SamAccountName -GivenName ("xx" + $(Get-ADuser -Identity $user.SamAccountName).GivenName)
}


来源:https://stackoverflow.com/questions/51544903/how-to-edit-only-the-firstname-givenname-of-multiple-users-and-import-with-csv

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