N.Ma
N.Ma

Reputation: 31

Why can't I update this attribute using the Set-ADUser PowerShell cmdlet?

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

Answers (1)

mklement0
mklement0

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:

  • you need to fix your Get-ADUser call,
  • and you should also add code that detects the case of that call unexpectedly returning no objects.

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

Related Questions