I am trying to add members to a AD group based on a value in the "title" attribute. I have about 30 different titles I want to use. Is there a way to write the command without 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 if their "location" attribute is "85c" or location "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}
CodePudding user response:
You can use the -in to specify list of values to compare with the title attribute
Here's an example :
$titles = "SECSCH", "SEC12", "LTOSEC", "LTO12"
Get-ADUser -Filter {title -in $titles} | ForEach-Object {
Add-ADGroupMember "SDK test print color" $_.SamAccountName
}
on the same strategy, you can exclude locations with operator -notin
$excludedLocations = "85c", "42c"
Get-ADUser -Filter {title -eq "custod" -and locationNumber -notin $excludedLocations} | ForEach-Object {
Add-ADGroupMember "SDK test print convert" $_.SamAccountName
}
CodePudding user response:
I use a procedural method to build this kind of thing into an LDAPfilter, which is easier to construct than a load of -or
statements, I feel.
$titles = @'
SECSCH
LTOSEC
???12
'@ -split '\r?\n'
# begin filter
## (&(samAccountType=805306368) is not really needed for Get-Aduser
$filter = "(&(samAccountType=805306368)(|"
# append each title
$titles | Foreach { $filter = "(title=$_)"}
# end filter
$filter = "))"
# filter = (&(samAccountType=805306368)(|(title=SECSCH)(title=SEC12)(title=LTOSEC)(title=???12)))
Get-Aduser -ldapfilter $filter
Notice I slipped a wildcard in the list. For example, that one will catch all titles exactly 5 chars long ending with "12". There may be shortcuts like that you can use in your environment.
If you use a wildcard query, but want to exclude some possible results, you can always add NOT clauses (make sure they're inside an AND clause, not inside the OR clause!):
(&(samAccountType=805306368)(!title=SOP12)(|...
Also remember -searchbase
to start from specific OUs if that might help you use wildcards or just better target sets of users with less noise/filtering required.