2017-05-08 111 views
0

我需要能够在Powershell中搜索活动用户时排除多个OU。 OU的列表存储在数据表中,当新的OU需要排除时可以更新。我想不出动态排除这些组织单位,即不需要为了添加新Powershell排除多个OU

(`$_.distinguishedname -notlike "*OU1*") 

每个OU更新脚本的方式。

我一直在尝试这个好几个小时,没有快乐。我甚至已经尝试通过数据表循环创建过滤器,如

$ToReturn = "(`$_.distinguishedname -notlike ""*$Row[0]*"")" 

然后添加

$ToReturn = $ToReturn + " -and (`$_.distinguishedname -notlike ""*$Row[0]*"")" 

后续排除但它忽略了变量。

更新1:代码返回用户::

$users = Get-ADUser -SearchBase $SourceOu -Server $Domain -Filter { 
     whenCreated -lt $DisableDate 
     -and PasswordNeverExpires -eq $False 
     }|? {$ExludedOUs} 

其中$ ExcludedOUs是,我需要的动态添加的等效的方式为每个($ _的distinguishedName -notlike “OU1”。)排除在数据表中。

非常感谢提前!

刘易斯

+2

' “” * $行[0] * “”'应该是' “” * $($行[0])*“”' –

+0

我想我们需要更多关于如何存储/检索这些排除的信息。我相信你可以使用'''''{'{'+'($ exclusions |%{“distinguishedname -notlike'$ _'”})-join'-and')+'}''这应该为'$ Exclusions'中的每个项目提供'{distinguishedname -notlike'X'和distinguishedname -notlike'Y'}'。 – TheMadTechnician

+0

谢谢你的评论。 Mathias - 我按照建议更新了它,但仍然无法使用。我已更新该帖子以进一步解释 @TheMadTechnician - 它存储在一个SQL表中,我可以循环,只是不知道如何把它放在一起! :-) –

回答

0

你可以使用-notmatch|正则表达式运营商加入您的排除:

$OURegex = $ExcludedOUs -Join '|' 
$users = Get-ADUser -SearchBase $SourceOu -Server $Domain -Filter { 
    whenCreated -lt $DisableDate 
    -and PasswordNeverExpires -eq $False 
    } | Where-Object {$_.DistinguishedName -notmatch $OURegex} 
+0

嗨@BenH,我尝试了下面的建议,但仍然没有过滤掉,我做错了什么? ' 功能GetListOfExcludedOUs() { 的foreach(在$ $ Result.Rows行) { $ ToReturnArray + = $行[0] } 返回$ ToReturnArray } $ ExludedOUs = GetListOfExcludedOUs - 加入 '|' $ users = Get-ADUser -SearchBase $ SourceOu -Server $ Domain -Filter { whenCreated -lt $ DisableDate -and PasswordNeverExpires -eq $ False } ? {$ _。distinguishedname -notmatch $ ExludedOUs}' –

+0

我发现了一些变化,因为我注意到我的代码与您的代码不同,现在它正在运行!非常感谢您的帮助! –

+0

@LewisHoulden太好了。很高兴它的作品。如果答案适用于接受它的最佳做法。 – BenH