Powershell-批量互换域用户属性信息
程序员文章站
2023-12-30 15:16:04
...
需求描述:
因生产环境数据接口需求,需要对某时间段已上线用户属性进行批量互换,涉及字段EmployeeNumber,雇员
环境信息:
Windows Server 2012 R2 ActiveDirectory
操作步骤:
PS。操作之初,建议先对当前环境属性字段进行备份导出操作。
方法一:
1.过滤出某时间段创建帐户信息,并导出域帐号EmployeeNumber,雇员ID字段;
$date=Get-Date
$oldday=(Get-Date).AddDays(-180)
Get-ADUser -Filter * -Properties * -SearchBase "OU=Old,OU=Staff,DC=a,DC=com" |?{$_.whenCreated -le $date -and $_.whenCreated -ge $oldday} |`
Select-Object name,samaccountname,userPrincipalName,EmployeeNumber,EmployeeID | `
Export-Csv C:\New0505.csv -Encoding UTF8 -NoTypeInformation
2.将表格数据进行按需调整,去掉ID字段为空的用户信息,并保存CSV文本格式为UTF8
3.执行导入用户信息操作,并查看当前各字段对应信息属性
Import-Csv 'C:\New0505.csv' | select SamAccountName,EmployeeNumber,EmployeeID
4.如信息无误,执行批量替换操作
4.1如ID与号码字段位置无调整,执行如下命令:
Import-Csv 'C:\New0505.csv' | ForEach-Object { Set-ADUser -Identity $_.SamAccountName -EmployeeNumber $_.EmployeeID -EmployeeID $_.EmployeeNumber }
4.2如ID与编号字段已调整,则按照正常替换格式替换,执行如下命令:
Import-Csv 'C:\New0505.csv' | ForEach-Object { Set-ADUser -Identity $_.SamAccountName -EmployeeNumber $_.EmployeeNumber -EmployeeID $_.EmployeeID }
查看替换后属性字段信息
Import-Csv 'C:\New0505.csv' | ForEach-Object { get-ADUser -Identity $_.SamAccountName -Properties * |select SamAccountName,EmployeeNumber,EmployeeID }
5.完成替换操作
方法二:
PS如当前环境中数据均无须调整,可直接执行替换操作,具体如下:
1.以OU为例介绍,查看当前OU下用户相关属性:
Get-ADUser -SearchBase "OU=Old,OU=Staff,DC=a,DC=com" -Filter * -Properties * |select SamAccountName,EmployeeNumber,EmployeeID
2.执行批量互换当前属性操作:
Get-ADUser -SearchBase "OU=Old,OU=Staff,DC=a,DC=com" -Filter * -Properties * |select SamAccountName,EmployeeNumber,EmployeeID |ForEach-Object { Set-ADUser -Identity $_.SamAccountName -EmployeeNumber $_.EmployeeID -EmployeeID $_.EmployeeNumber }
3.再次查看当前OU下用户属性,发现用户属性已变更完成。
Get-ADUser -SearchBase "OU=Old,OU=Staff,DC=a,DC=com" -Filter * -Properties * |select SamAccountName,EmployeeNumber,EmployeeID
综合:对方法一脚本进行优化操作,批量互换某时间段用户属性字段信息:
$date=Get-Date
$oldday=(Get-Date).AddDays(-180)
Get-ADUser -Filter * -Properties * -SearchBase "OU=Old,OU=Staff,DC=a,DC=com" |?{$_.whenCreated -le $date -and $_.whenCreated -ge $oldday} |`
Select-Object name,samaccountname,userPrincipalName,EmployeeNumber,EmployeeID |
forEach-Object { Set-ADUser -Identity $_.SamAccountName -EmployeeNumber $_.EmployeeID -EmployeeID $_.EmployeeNumber }
完成本次需求操作。