Reputation: 25
I am trying to add members to a AD group based on a value in the "title" attribute. I have about 30 different tiles i want to use. Is there a way to write the command witout 30 "OR" statements?
Thanks
Get-ADuser -filter {(title -eq "SECSCH") -or (title -eq "SEC12") -or (title -eq
"LTOSEC") -or (title -eq "LTO12")} | %{Add-ADGroupMember "SDK test print color"
$_.SamAccountName}
Also, for another group I would like All "custod" in title except at location "85c" and "42c" Below is where i am at.
Get-ADuser -filter {(title -eq "custod") -and (locationNumber -ne "85c") -or (title -eq
"custod") -and (locationNumber -ne "42c")} | %{Add-ADGroupMember "SDK test print
convert" $_.SamAccountName}
Upvotes: 0
Views: 467
Reputation: 1268
I provided a different answer to the first at the other place it was asked, using -Ldapfilter
, but I feel @Onyx's answer here is probably more intuitive if you're not so comfortable with that. It's efficient in that you're only getting the objects you need, not grabbing every account out of AD and throwing away most of them.
To be honest, doing -Filter 'title -like "*"'
would be better than nothing if you MUST use a Where
clause.
For the second question (as described in the comments), the same applies with maybe building an LDAPfilter or @Onyx's method of creating an array for your customlocations
and doing a Foreach
through those.
Or again, at the very least, do -Filter '(employeeType -ne "student") -and (CustomLocation -like "*")'
before the Where
.
Upvotes: 0
Reputation: 61263
The -Members
parameter can take an array of ADPrincipal objects so what you can do instead of using so many 'OR's in the Filter is using a Where-Object
clause afterwards.
This will allow you to use operators like -contains
or -match
$titles = "SECSCH","SEC12","LTOSEC","LTO12" # your 30+ titles here
$users = Get-ADUser -Filter * -Properties Title | Where-Object { $titles -contains $_.Title }
Add-ADGroupMember -Identity "SDK test print color" -Members $users
As for your second code change the Filter to below
$filter = "Title -eq 'custod' -and (locationNumber -ne '85c' -and locationNumber -ne '42c')"
$users = Get-ADUser -Filter $filter -Properties Title, locationNumber
Add-ADGroupMember -Identity "SDK test print convert" -Members $users
Note: the property locationNumber
is AFAIK not a standard attribute in AD. Is that a custom property in your organization or do you perhaps mean something else like Division
or EmployeeNumber
?
Upvotes: 0
Reputation: 45
For your first issue you can create an array which contains your titles and browse it.
Example :
$Titles = "SECSCH","SEC12","LTOSEC","LTO12"
foreach($Title in $Titles){
Get-ADuser -filter {title -eq $Title} | %{Add-ADGroupMember "SDK test print color" $_.SamAccountName}
}
Upvotes: 1