Get-ADUser -Filter 'l -like "Atlanta"' -SearchBase 'OU=atl,DC=ego,DC=ga,DC=com' -Properties DisplayName | % {Set-ADUser $_ @{GMLocation='ATL'} }
I am trying to update the GMLocation
of all users that have a location of Atlanta with the code above. Can someone help me figure out why it does not work?
CodePudding user response:
Set-ADUser
expects you to use -Replace <hashtable>
or -Add <hashtable>
:
Get-ADUser -Filter "l -like 'Atlanta'" -SearchBase 'OU=atl,DC=ego,DC=ga,DC=com' |
Set-ADUser -Replace @{ GMLocation = 'ATL' }
You're also using -Filter "l -like 'Atlanta'"
but no wildcards for -like
, if you're looking for an exact match of Atlanta
then use -eq
for equality: -Filter "l -eq 'Atlanta'"
. If instead, you're looking for partial match you should use -like
but add wildcards (*
): -Filter "l -like '*Atlanta*'"
.
If you want to add error handling to your code, you can use a try { }
catch { }
statement:
$ErrorActionPreference = 'Stop'
$param = @{
Properties = 'GMLocation'
SearchBase = 'OU=atl,DC=ego,DC=ga,DC=com'
Filter = "l -like 'Atlanta'"
}
Get-ADUser @param | ForEach-Object {
$adusrSplat = @{ Identity = $_ }
if($_.GMLocation) {
# If the user already have this Attribute Set
# Replace it
$adusrSplat['Replace'] = @{ GMLocation = 'ATL' }
}
else {
# Else, Add this new Attribute for the User
$adusrSplat['Add'] = @{ GMLocation = 'ATL' }
}
try {
Set-ADUser @adusrSplat
}
catch {
Write-Warning $_.Exception.Message
}
}