Reputation: 31
I am trying to update the city
attribute for users in a specific ou
using this script, but it does not work. The script completes without error. When I check the users, the city
is still blank.
$users = Get-ADUser -Filter * -SearchBase 'OU=...' -Properties SamAccountName
foreach ($user in $users){
Set-ADUser -identity $user.SamAccountName -City 'Alice'
}
Upvotes: 1
Views: 2025
Reputation: 437208
It sounds like your Get-ADUser
returns nothing, so the foreach
loop is never entered.
Get-ADUser
with the -Filter
parameter doesn't fail if no matches are found, it quietly returns an empty collection.
A foreach
loop over an empty collection or $null
is simply never entered, so overall you get a quiet no-op.
Note that you never need -Properties SamAccountName
in a Get-ADUser
call, because -Properties
is only needed to return additional properties for every result object, whereas SamAccountName
is part of the default set of properties.
Therefore:
Get-ADUser
call, The following snippet demonstrates the latter, and it also streamlines your command by passing the output from Get-ADUser
directly to 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." }
Upvotes: 1