简体   繁体   中英

Run AD search for users not in Group excluding OU's

Good Afternoon

I am trying to create a PS script which pulls all users not in a certain Security group. I have managed to get this to work fine. However i require it to omit certain OU's as i don't want certain accounts included in this process like terminated users and support accounts for examples.

So i created the below to do this but it seems to fail. Its where i have tried to add some filtering. Can someone help put this in the right direction?

import-Module activedirectory
$results = @()
$users = Get-ADUser  -Properties memberof -Filter {enabled -eq $true} | ? {$_.DistinguishedName -notlike "*,OU=Exchange,OU=Support Accounts,OU=Terminated Users and Computers do not use,OU=TerminatedEmployeesContractors,OU=TestAccounts*"} * 
$ExportPath = 'c:\app\users_in_ou1.csv'
foreach ($user in $users) {
    $groups = $user.memberof -join ';'
    $results += New-Object psObject -Property @{'User'=$user.name;'Groups'= $groups}
    }
$results | Where-Object { $_.groups -notmatch 'SG_XXXXXXXXXXX' } | Select-Object user | export-csv $ExportPath

Thanks

I would build a regex from all OUs that should be excluded from the search by joining the strings with the regex 'OR' character ( | ) and use the -notmatch operator.
Because there may be characters in these strings that have special meaning in regex, use [Regex]::Escape() on each before joining them.

Something like below:

Import-Module ActiveDirectory

# create a regex from an array of OUs to exclude by 'OR-ing' them with the pipe character
$excludeOUs = ('OU=Exchange','OU=Support Accounts','OU=Terminated Users and Computers do not use',
               'OU=TerminatedEmployeesContractors','OU=TestAccounts' | ForEach-Object {[Regex]::Escape($_)}) -join '|'

$ExportPath = 'c:\app\users_in_ou1.csv'

# get a list of objects not having any of the excluded OUs in their DistinguishedName
# and at the same time output objects with properties 'User' and 'Groups'
$users = Get-ADUser -Properties Name, MemberOf -Filter 'Enabled -eq $true' | 
              Where-Object {$_.DistinguishedName -notmatch $excludeOUs} |
              Select-Object @{Name = 'User'; Expression = {$_.Name}},
                            @{Name = 'Groups'; Expression = {($_.MemberOf -join ';')}}

# next filter this out further by excluding a certain group and export to Csv
$users | Where-Object { $_.Groups -notmatch 'SG_XXXXXXXXXXX' } | Export-Csv $ExportPath -NoTypeInformation

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM