使用 powershell 从 CSV 导入 AD 属性

Importing AD attributes from CSV using powershell

我是 PowerShell 的新手,我正在尝试使用 PowerShell 从 .csv 文件更新 AD 属性

下面是我的 csv 文件中的行以及我要更新的属性

部门 > 部门

部门 > 部门

服务 > 信息

EmployeeFullname(用于识别对象)

LineMangerFullname > 经理

成本中心 > 部门编号

职位名称 > 职位

到目前为止,我只能更新 Active Directory 中的 Department、Division、Title(职务)和经理属性

我正在使用下面的脚本成功更新这些属性

$Users = Import-CSV C:\Users\user\Documents\CurrentWork\userlist.csv

ForEach ($User in $Users) {
    Get-ADUser -Filter * -property displayname | where {$_.displayname -eq $User.EmployeeFullName} | Set-ADUser -department $User.Department -Division $User.Division -Title $User.JobTitle -Manager $User.LineMangerFullname
}

然而,当将 infodepartmentNumber 添加到脚本(如下)时,它失败了:

"parameter name 'info' is ambiguous" and A parameter cannot be found that matches parameter name 'departmentNumber'
$Users = Import-CSV C:\Users\user\Documents\CurrentWork\userlist.csv

ForEach ($User in $Users) {
    Get-ADUser -Filter * -property displayname | where {$_.displayname -eq $User.EmployeeFullName} | Set-ADUser -department $User.Department -Division $User.Division -Title $User.JobTitle -Manager $User.LineMangerFullname -info $User.Service -departmentNumber $User.'Cost Centre'
}

有谁知道我做错了什么或者我怎样才能让这些更新,还有我怎样才能导出结果以查看更新是否成功?真的卡在这里

Set-ADUser 不会将 所有可能的 AD 架构属性 公开为参数,仅公开一组有限的常见用户属性 - 以及 info 属性(或在某些工具中显示的“注释”)是不是它具有参数的工具之一。

要设置没有相应参数的 属性 的值,请使用 -Replace-Add 参数,通过传递描述更新:

... |Set-ADUser -Replace @{ info = "new info value" }

如评论所述,对于 Set-AccountName,Manager 属性 只能是 DistinguishedName, GUID, SID or SamAccountName 之一。显然,CSV 不包含任何内容,$User.LineMangerFullname 包含经理的完整名字和姓氏。

为此,您需要使用另一个 Get-ADUser 调用从该经理那里检索有效的 属性。

接下来,正如 Mathias R. Jessen 在他的 中已经指出的那样,并非所有属性都直接 在 Set-ADUser 的参数中可用,因此对于一些你将不得不使用 -Replace @{property = value} 语法。

最后,我建议在 cmdlet 上使用 Splatting,这些 cmdlet 可能需要很多参数才能使代码 clean/maintainable.

尝试

$Users = Import-CSV C:\Users\user\Documents\CurrentWork\userlist.csv

foreach ($User in $Users) {
    $adUser = Get-ADUser -Filter "DisplayName -eq '$($User.EmployeeFullName)'" -Properties DisplayName -ErrorAction SilentlyContinue
    if ($adUser) {
        # set up a Splatting Hashtable for the Set-ADUser cmdlet
        $userParams = @{
            Department = $User.Department
            Division   = $User.Division
            Title      = $User.JobTitle
        }
        $manager = Get-ADUser -Filter "Name -eq "$($User.LineMangerFullname) -ErrorAction SilentlyContinue
        # if we did find a manager, add property 'Manager' to the Hashtable
        if ($manager) { $userParams['Manager'] = $manager.DistinguishedName }

        # use the Hash to splat all known parameters to Set-ADUser
        $adUser | Set-ADUser $userParams
        # next , update the attributes that have no direct parameter in Set-ADUser
        $adUser | Set-ADUser -Replace @{ info = $User.Service; departmentNumber = $User.'Cost Centre' }
    }
    else {
        Write-Warning "User $($User.EmployeeFullName) could not be found"
    }
}