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



下午好

我正在尝试创建一个PS脚本,该脚本将不在某个安全组中的所有用户拉出。我已经设法让它正常工作。但是,我要求它省略某些 OU,因为我不希望在此过程中包含某些帐户,例如终止的用户和支持帐户。

所以我创建了以下内容来执行此操作,但它似乎失败了。这是我尝试添加一些过滤的地方。有人可以帮助解决这个问题吗?

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:appusers_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

谢谢

我会通过连接带有正则表达式"OR"字符 (|( 的字符串并使用 -notmatch 运算符,从所有应该从搜索中排除的 OU 构建一个正则表达式。
由于这些字符串中可能存在在正则表达式中具有特殊含义的字符,因此请在连接它们之前对每个字符串使用 [Regex]::Escape()

如下所示:

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:appusers_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

最新更新