简体   繁体   English

对组中不包括 OU 的用户运行 AD 搜索

[英]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.我正在尝试创建一个 PS 脚本,该脚本会拉出不在某个安全组中的所有用户。 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.但是,我要求它省略某些 OU,因为我不希望在此过程中包含某些帐户,例如终止用户和支持帐户。

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.我将从所有应该从搜索中排除的 OU 构建一个正则表达式,方法是使用正则表达式“OR”字符 ( | ) 连接字符串并使用-notmatch运算符。
Because there may be characters in these strings that have special meaning in regex, use [Regex]::Escape() on each before joining them.因为这些字符串中可能存在在正则表达式中具有特殊含义的字符,所以在加入它们之前对每个字符使用[Regex]::Escape()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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