将AD属性值替换为csv文件头值



我想替换AD属性"userPrincipalName";根据CSV文件头值的值以下是csv文件(group.csv(包含的

sAMAccountName
--------------
test.user1    
test.user2    

低于脚本

$data = Import-Csv -Path .group.csv -Header 'sAMAccountName'
foreach($user in $data){
Get-ADUser -Filter {sAMAccountName -eq "$($user.sAMAccountName)"} | Set-ADUser -Replace @{userPrincipalName="$($user.sAMAccountName)@RES.GROUP"}
}

这里我想替换AD属性";userPrincipalName";带有csv文件中sAMAccountName的值,类似于sAMAccountName@RES.GROUP

这个脚本不起作用,有人能纠正吗?

好的,由于您的注释显示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的用户时,文件中的任何错误都不会导致代码退出。相反,在这种情况下,您将看到有关它的警告,代码将继续处理其余数据。


值得一提的是,您可以在Get-ADUserSet-ADUsercmdlet上使用参数-Server,以确保使用相同的域服务器(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'
}

只将users SamAccountName属性写入csv文件似乎是浪费。。特别是由于默认情况下Get-ADUser已经返回这些属性:DistinguishedName、Enabled、GivenName、Name、ObjectClass、ObjectGUID、SamAccountName、SID、Surname、UserPrincipalName

相关内容

  • 没有找到相关文章

最新更新