【问题标题】:Update user AD attributes from CSV file using powershell使用 powershell 从 CSV 文件更新用户 AD 属性
【发布时间】:2022-01-18 08:23:54
【问题描述】:

我正在尝试使用 powershell 从 CSV 文件更新 AD 用户属性:title、physicalDeliveryOfficeName 和部门。我是powershell的新手,所以我需要一些帮助。 (请,并提前感谢) 所以,想法是匹配的过滤器是 displayName 属性,我使用的脚本是:

Import-Module ActiveDirectory 
$csv = Import-Csv C:\Temp\AD_import_test.csv 
foreach ($line in $csv) {
$displayName = $line.displayName
Get-ADUser -Filter {displayName -eq $displayName} |
Set-ADUser -Title $($csv.title) -department $($csv.Department) -physicalDeliveryOfficeName $($csv.physicalDeliveryOfficeName) }

但脚本返回错误:

 Set-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Title'. Specified method is not supported.
    At line:6 char:19
    + Set-ADUser -Title $($csv.title) -department $($csv.Department) -physi ...
    +                   ~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.SetADUser
 
Set-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Title'. Specified method is not supported.
At line:6 char:19
+ Set-ADUser -Title $($csv.title) -department $($csv.Department) -physi ...
+                   ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.SetADUser 

【问题讨论】:

  • 顺便说一句,-Filter 真的应该是一个 字符串 而不是脚本块,所以使用 -Filter "DisplayName -eq '$displayName'"

标签: powershell csv import active-directory


【解决方案1】:

您使用了错误的变量来分配这些值。在您的脚本中 $csv 包含整个 .csv 文件,但在您的 foreach 行中,您将每一行加载到 $line 中,这就是您需要设置值的地方。

因此,从本质上讲,$($csv.title) 等于所有标题字段,而不仅仅是您感兴趣的字段。这就是为什么您收到错误消息说它是 System.Object[] 而不是 System .String... 因为它不是一个单一的值。

我注意到您在 "$displayName = $line.displayName" 行上是正确的,所以它只是需要更新的 Set-ADUser 行,如:

Set-ADUser -Title $($line.title) -department $($line.Department) -physicalDeliveryOfficeName $($line.physicalDeliveryOfficeName) }

编辑: 此外,像这样的一个有用的技巧是添加一些 Write-Output 行来显示变量内容是什么,这样您就可以检查它们是否符合您的期望,例如:

Write-Output $($line.title)

然后在 $line.title 的情况下应该向您显示一个值,而如果您这样做 $($csv.title) 它将返回多个值并告诉您问题出在哪里。

【讨论】:

  • 谢谢大家的解释!
【解决方案2】:

除了set-aduser 需要将$csv 替换为$line 之外,您的代码对我来说似乎不错

Import-Module ActiveDirectory 
$csv = Import-Csv C:\Temp\AD_import_test.csv 
foreach ($line in $csv) {
$displayName = $line.displayName
Get-ADUser -Filter {displayName -eq $displayName} |
Set-ADUser -Title $($line.title) -department $($line.Department) -physicalDeliveryOfficeName $($line.physicalDeliveryOfficeName) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2015-02-19
    • 2015-06-15
    相关资源
    最近更新 更多