【问题标题】:PowerShell - Change attributes BULK to a list of usersPowerShell - 将属性 BULK 更改为用户列表
【发布时间】:2020-10-18 20:34:21
【问题描述】:

我有一个 CSV 文件,其中包含 A 列上的用户列表 (samaccountname)。 在其他列上,我想设置其他属性值 对于这些用户中的每一个:

“办公室”在 B 列,“部门”在 C 列,公司在 D 列:

请帮助组装正确的 Powershell Synatx。

到目前为止,我已经尝试了以下方法:

Import-Module Activedirectory
$Attribcsv=Import-csv "D:\powershell\ADuserinformation\SetUserAttributes.csv"
ForEach ($User in $Attribcsv)
{
Set-ADUser $User.samaccountname -department $._Department
}

使用具有两列的不同 csv:sAMAcountName,Department

但我得到了一个错误:

【问题讨论】:

  • 请展示您的尝试
  • 已编辑,使用我尝试过的代码。

标签: powershell


【解决方案1】:

您可以这样尝试(首先使用Get-ADUser 获取用户的SAM 帐户名称,然后通过管道传递到Set-ADUser 以设置属性):

Import-Module Activedirectory
$Attribcsv=Import-csv "D:\powershell\ADuserinformation\SetUserAttributes.csv"
ForEach ($User in $Attribcsv)
{
Get-ADUser -Identity $User.Users | Set-ADUser -department $._Department
}

【讨论】:

  • 哈桑你好,我得到的错误与我在尝试时提到的完全相同。 "" Get-ADUser : 无法验证参数 'Identity' 上的参数。参数为空。为参数提供一个有效值,然后再次尝试运行该命令。""
  • 如果“用户”列是您的 SAM 帐户名,请尝试编辑
  • 也试过编辑,同样的错误。这很奇怪,我在使用其他 csv/PowerShell 时也遇到了这个错误。
  • 好的,我解决了,CSV 有问题,我重新打开它并修复它。现在我有另一个问题。对于部门值,我有另一个值,所以我试图用现在的语法替换这个值,它不起作用,有没有可以用来替换当前值的语法?
【解决方案2】:

聚会有点晚了,但我个人不会在这里使用-Identity 参数,因为如果输入 CSV 中有拼写错误,脚本就会被炸毁。

一个更宽容的选择是像这样使用-Filter

Import-Module Activedirectory -ErrorAction SilentlyContinue

$AttribCsv = Import-csv "D:\powershell\ADuserinformation\SetUserAttributes.csv" | ForEach-Object {
    $accountName = $_.Users  # make sure the header for this column is correct here!
    # now try and find a valid user object using Filter
    $user = Get-ADUser -Filter "SamAccountName -eq '$accountName'" -Properties Office, Company, Department -ErrorAction SilentlyContinue
    if ($user) {
        $user | Set-ADUser -Department $_.Department -Company $_.Company -Office $_.Office
        # or use -Replace:
        # $user | Set-ADUser -Replace @{Department = $_.Department; Company = $_.Company; Office = $_.Office}
    }
    else {
        Write-Warning "User with SamAccountName '$accountName' not found.."
    }
}

请注意,如果任何属性的值为 null 或空值,Set-ADUser cmdlet 将返回错误。 检查您的输入 CSV。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多