关于powershell:Set-ADuser:是否可以使用DisplayName更新AD中的用户属性?

Set-ADuser: Is it possible to use DisplayName to update a user attribute in AD?

我需要使用Powershell为AD中的多个用户更新属性employeeID。 不幸的是,我没有他们的用户名或samaccountname,只有DisplayName。 我可以使用DisplayName作为过滤器来吸引用户,但是在使用set-aduser时不起作用。 有什么方法可以使用get-aduser获取samaccountname,然后使用它通过set-aduser更新用户?

另外,请注意,脚本不要覆盖任何现有值,这一点很重要。

我当前的(非功能性)脚本:

1
2
3
4
5
6
7
8
$csv = Import-Csv c:\\test\\users.csv

foreach ($line in $csv) {
    $ADUserObject = Get-ADUser -Filter"DisplayName -eq '$line.displayname'" -Properties employeeID
    if ($null -eq $ADUserObject.EmployeeID) {
    Set-ADUser -Filter"DisplayName -eq '$line.displayname'" -employeeID $line.employeeid
    }
}

CSV文件如下所示:

1
2
employeeid,GivenName,Surname,displayname
489900,Angela,Davis,Angela Davis

任何意见或建议表示赞赏,谢谢!


如所评论,这实际上是该问题的重复,但是由于在那儿,OP没有投票或接受任何给定的答案,因此我无法将其标记为重复。

正如Mathias R. Jessen已经解释的那样,您使用的过滤器是错误的。 同样,Set-ADUser上没有与之对应的Get-ADUser上的-Filter参数。

这应该做您想要的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Import-Csv -Path 'c:\\test\\users.csv' | ForEach-Object {
    $ADUserObject = Get-ADUser -Filter"DisplayName -eq '$($_.displayname)'" -Properties DisplayName, employeeID -ErrorAction SilentlyContinue
    if ($ADUserObject) {
        # check if this user already has an EmployeeId filled in
        if ($ADUserObject.EmployeeID) {
            Write-Host"User $($ADUserObject.DisplayName) already has EmployeeId $($ADUserObject.EmployeeID)"
        }
        else {
            Write-Host"Setting EmployeeID $($ADUserObject.EmployeeID) for user $($ADUserObject.DisplayName)"
            $ADUserObject | Set-ADUser -EmployeeID $_.employeeid
        }
    }
    else {
        Write-Warning"User $($_.DisplayName) could not be found"
    }
}