为什么可以';我是否使用Set-ADUser PowerShell cmdlet更新此属性?

为什么可以';我是否使用Set-ADUser PowerShell cmdlet更新此属性?,powershell,Powershell,我试图使用此脚本更新特定ou中用户的city属性,但它不起作用。脚本完成时没有错误。当我检查用户时,城市仍然为空 $users = Get-ADUser -Filter * -SearchBase 'OU=...' -Properties SamAccountName foreach ($user in $users){ Set-ADUser -identity $user.SamAccountName -City 'Alice' } 听起来您的Get ADUser没有返回任何内容,因

我试图使用此脚本更新特定
ou
中用户的
city
属性,但它不起作用。脚本完成时没有错误。当我检查用户时,
城市
仍然为空

$users = Get-ADUser -Filter * -SearchBase 'OU=...' -Properties SamAccountName
foreach ($user in $users){
    Set-ADUser -identity $user.SamAccountName -City 'Alice'
}

听起来您的
Get ADUser
没有返回任何内容,因此永远不会进入
foreach
循环

Get ADUser
使用
-Filter
参数,如果没有找到匹配项,它会安静地返回一个空集合

在空集合上的
foreach
循环或
$null
根本就不会被输入,所以总体上你会得到一个安静的no-op

请注意,在
Get ADUser
调用中,您永远不需要
-Properties-SamAccountName
,因为
-Properties
只需要返回每个结果对象的附加属性,而
SamAccountName
是默认属性集的一部分

因此:

  • 您需要修复您的
    Get ADUser
    呼叫
  • 您还应该添加代码来检测调用意外不返回任何对象的情况
下面的代码片段演示了后者,它还通过将
Get ADUser
的输出直接传递到
Set ADUser
来简化您的命令:

# Get the users of interest and pass them to the Set-ADUser call to update
# the City property.
# Note the use of -OutputVariable users, which saves the output from 
# Get-ADUser in variable $users
Get-ADUser -OutputVariable users -Filter * -SearchBase 'OU=...' | Set-ADUser -City 'Alice'

# Report terminating error if no users were found.
# Note: -not $users returns $true if $users is an empty collection
#       (or a similarly "falsy" value such as $null, 0, or '').
if (-not $users) { Throw "Get-ADUser unexpectedly returned nothing." }

为什么不行?嗨,妈,欢迎来到stackoverflow!试着对你的问题做一个更详细的描述,我们会尽力帮助你!我尝试更新特定OU中所有用户的城市属性。当我运行上面的脚本时,它没有将城市设置为Alice。好的,那么它说了什么?错误是什么?它没有返回任何错误,脚本已完成,但在检查时,这些用户的城市字段仍然为空。