Modify users based on Office location
I can't get this to work... any ideas? Basically, even if a user is in Chicago, the claim is the user isn't and falls in the else statement.
I basically want to collect all users in AD.
Then I want to look at their Office l开发者_如何学Cocation and based on where they are located, set their address....
$Users = Get-ADGroupMember "Domain Users" -recursive | Select-Object sAMAccountName
foreach ($User in $Users)
{
if
(Get-ADUser -filter {saMAccountName -eq '$User' -and Office -eq "Chicago"})
{
Set-ADUser -StreetAddress "66 Chicago Rd" -City "Chicago" -PostalCode "60618" -State "IL" -Country "US" -Replace @{ co="United States"; countryCode="804" }
}
else
{
(echo $User " not in Chicago!")}
}
Can you try this :
$Users = Get-ADGroupMember "Domain Users" -recursive | Select-Object sAMAccountName
foreach ($User in $Users)
{
if
(Get-ADUser -filter {saMAccountName -eq $User.saMAccountName -and Office -eq "Chicago"})
{
Set-ADUser -StreetAddress "66 Chicago Rd" -City "Chicago" -PostalCode "60618" -State "IL" -Country "US" -Replace @{ co="United States"; countryCode="804" }
}
else
{
(echo $User " not in Chicago!")}
}
I just replace
saMAccountName -eq '$User'
by
saMAccountName -eq $User.saMAccountName
Try this, for some reason $obj.Property is not expanded in the filter scriptblock. I used Foreach-Object instead of Select-Object to extract the values of sAMAccountName. You were also missing the user object to set in the Set-ADUser command:
$Users = Get-ADGroupMember "Domain Users" -recursive | Foreach-Object {$_.sAMAccountName}
foreach ($User in $Users)
{
if (Get-ADUser -Filter {sAMAccountName -eq $User -and Office -eq 'Chicago'})
{
$user | Set-ADUser -StreetAddress '66 Chicago Rd' -City Chicago -PostalCode 60618 -State IL -Country US -Replace @{ co='United States'; countryCode=804 }
}
else
{
"$User not in Chicago!"
}
}
UPDATE:
You can also use the streaming nature of the cmdlets in question (process one object at a time) with the following one-liner:
Get-ADGroupMember 'Domain Users' -Recursive | Where-Object {$_.ObjectClass -eq 'user'} | Get-ADUser -Properties Office | Where-Object {$_.Office -eq 'Chicago'} | Set-ADUser -StreetAddress '66 Chicago Rd' -City Chicago -PostalCode 60618 -State IL -Country US -Replace @{ co='United States'; countryCode=804 }
精彩评论