好的,由于您的评论显示 CSV 文件确实没有标题,我建议将代码更改为:
$data = Import-Csv -Path .\group.csv -Header 'sAMAccountName'
foreach($user in $data) {
$adUser = Get-ADUser -Filter "SamAccountName -eq '$($user.sAMAccountName)'" -ErrorAction SilentlyContinue
if ($adUser) {
$newUPN = '{0}@res.group' -f $user.sAMAccountName
$adUser | Set-ADUser -UserPrincipalName $newUPN
}
else {
Write-Warning "No user with SamAccountName '$($user.sAMAccountName)' could be found.."
}
}
这样,当找不到具有该 samaccountname 的用户时,文件中的任何错误都不会导致代码退出。相反,在这种情况下,您将看到有关它的警告,并且代码将继续处理其余数据。
值得一提的是,您可以-Server
在cmdletGet-ADUser
和Set-ADUser
cmdlet 上使用参数,以确保使用相同的域服务器 (DC) 来设置新的 UPN。否则,您可以在一个 DC 上设置它,但正在查看另一个不会立即显示更改的 DC,因为服务器需要时间来同步。
现在我们已经解决了有关 CSV 的问题并回答您的评论:
如果您想将此作为两个脚本的解决方案来执行,请按照以下方法执行此操作
第 1 步:获取搜索 OU 中 UserPrincipalName 以 '*@test.group' 结尾的所有用户
$searchBase = "OU=Teams,OU=Prod,DC=RES,DC=TEST,DC=GROUP"
Get-ADUser -SearchBase $searchBase -Filter "UserPrincipalName -like '*@test.group'" |
# select ony the SamAccountName and write to CSV with column header
Select-Object SamAccountName | Export-Csv -Path .\group.csv -NoTypeInformation
第 2 步:阅读上面创建的 csv 和
$searchBase = "OU=Teams,OU=Prod,DC=RES,DC=TEST,DC=GROUP"
$data = Import-Csv -Path .\group.csv
$result = foreach($user in $data) {
$adUser = Get-ADUser -SearchBase $searchBase -Filter "SamAccountName -eq '$($user.sAMAccountName)'" -ErrorAction SilentlyContinue
# if we have a user object AND its UserPrincipalName is not as desired go ahead and change that
if ($adUser) {
if ($adUser.UserPrincipalName -notlike '*@res.test.group') {
$newUPN = '{0}@res.test.group' -f $user.sAMAccountName
$adUser | Set-ADUser -UserPrincipalName $newUPN
# output this user object to be collected in variable $result
$adUser
}
else {
Write-Host "User $($user.sAMAccountName) already has UPN '$($adUser.UserPrincipalName)'"
}
}
else {
Write-Warning "User with SamAccountName '$($user.sAMAccountName)' not found.."
}
}
# now that we have changed some users, create a second csv with all users that were actually changed
if (@($result).Count) {
$result | Select-Object SamAccountName | Export-Csv -Path .\Updatedgroup.csv -NoTypeInformation
}
else {
Write-Host 'No users needed updating'
}
仅将用户 SamAccountName 属性写入 csv 文件似乎是一种浪费。特别是因为Get-ADUser
默认情况下已经返回这些属性:DistinguishedName、Enabled、GivenName、Name、ObjectClass、ObjectGUID、SamAccountName、SID、Surname、UserPrincipalName