powershell批量修改AD域用户UPN后缀
(1)需求:一客户云端365有多个域名,想要本地用户同步到云端就要修改用户UPN后缀(没有根据OU划分,不是一个OU对应一个域名),根据实际情况,用户的邮件地址是和云端同步的,因此解决方案为根据用户的邮件地址后缀来更改用户登录名后缀。(第一次写windows的脚本,比较菜~)
Import-Module ActiveDirectory
$ou = 'OU=user,DC=effortjz,DC=club'
$adusers = Get-ADUser -SearchBase $ou -Filter * -Properties "*"
foreach($user in $adusers){
$newUPN = $user.emailaddress -match '(?<=(?:@))[a-z]*.[a-z]*'
$UPN = $($Matches.Values)
Set-ADUser $user -UserPrincipalName "$($user.samaccountname)@$UPN"
}
#导入ActiveDirectory模块
Import-Module ActiveDirectory
#根据ou来查找用户,不然会更改一些系统用户,组织单位名为user,域为effortjz.club
$ou = 'OU=user,DC=effortjz,DC=club'
#查找ou为user下的用户属性(包括Name,EmailAddress,PrincipalName等等)
$adusers = Get-ADUser -SearchBase $ou -Filter * -Properties "*"
foreach($user in $adusers){
#匹配每个用户emailaddress的后缀,(?<=):匹配某个字符之后的位置但不包括此字符
$newUPN = $user.emailaddress -match '(?<=(?:@))[a-z]*.[a-z]*'
# $Matches还会输出序号,$Matches.Values只输出匹配到的后缀
$UPN = $($Matches.Values)
#修改用户的UserPrincipalName为用户的samaccounname+电子邮件后缀名
Set-ADUser $user -UserPrincipalName "$($user.samaccountname)@$UPN"
}
(2)根据txt文件修改,把要修改的用户名写到Accounts_before_UPN_change.txt
Import-Module ActiveDirectory
$ImportPath = 'C:\Users\yolanda\Desktop\'
# importfiles
$before = 'Accounts_before_UPN_change.txt'
$newUPN = 'adtest.cn'
$adusers = Get-ADUser -Filter * -Properties UserPrincipalName
$fileusers = Get-Content $ImportPath$before
foreach ($user in $adusers){
foreach ($account in $fileusers){
if ($user.userprincipalname -eq $account){
Set-ADUser $user -UserPrincipalName "$($user.samaccountname)@$newUPN"
}
}
}