I need to be able to exclude multiple OUs when searching for Active Users in Powershell. The list of OUs is stored in a data table which can be updated when new OUs need excluding. I can't think of a way of excluding these OUs dynamically, ie not requiring to update the script in order to add a new
(`$_.distinguishedname -notlike "*OU1*")
for each OU.
I've been attempting this for a good few hours now with no joy. I've even tried creating the filter by looping through the data table, such as
$ToReturn = "(`$_.distinguishedname -notlike ""*$Row[0]*"")"
and then add
$ToReturn = $ToReturn + " -and (`$_.distinguishedname -notlike ""*$Row[0]*"")"
for subsequent exclusions however it ignores the variable.
UPDATE 1: Code to return users::
$users = Get-ADUser -SearchBase $SourceOu -Server $Domain -Filter {
whenCreated -lt $DisableDate
-and PasswordNeverExpires -eq $False
}|? {$ExludedOUs}
Where $ExcludedOUs is, I need a way of dynamically adding an equivalent of ($_.distinguishedname -notlike " OU1 ") for each Exclusion in the datatable.
Many thanks in advance!
Lewis
You could use -notmatch
and join your exclusions with |
regex operator:
$OURegex = $ExcludedOUs -Join '|'
$users = Get-ADUser -SearchBase $SourceOu -Server $Domain -Filter {
whenCreated -lt $DisableDate
-and PasswordNeverExpires -eq $False
} | Where-Object {$_.DistinguishedName -notmatch $OURegex}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.