Powershell在where-object

时间:2016-12-30 16:47:29

标签: powershell

请事先原谅我,因为我可能没有在这里正确定义:

我有一个脚本可以查询特定OU中用户的Active Directory,同时排除该OU中的十几个OU。该脚本有效,但它有点混乱,因为我声明了13个代表各种OU的变量并在where-object中引用它们。由于我正在查询多个域,因此还存在一个foreach循环。我想找到一种方法来引用我在一个集合或数组中的查询中排除的所有OU,并在我的where-object中循环它,以避免在where-object中引用13个变量。谁能指出我正确的方向? (以下代码不包括OU变量定义) 现有代码:

(Get-ADForest).domains | foreach {
    Get-ADUser -filter {Enabled -eq $True} -properties * -SearchBase "OU=Accounts,$((Get-ADDomain -Server $_).DistinguishedName)" -Server $_ | 
    where-object {$_.Title -notmatch "Volunteer" -and $_.DistinguishedName -notmatch $excludeOU1 -and $_.DistinguishedName -notmatch $excludeOU1 -and $_.DistinguishedName -notmatch $excludeOU2 -and 
      $_.DistinguishedName -notmatch $excludeOU3 -and $_.DistinguishedName -notmatch $excludeOU4 -and $_.DistinguishedName -notmatch $excludeOU5 -and $_.DistinguishedName -notmatch $excludeOU6 -and 
      $_.DistinguishedName -notmatch $excludeOU7 -and $_.DistinguishedName -notmatch $excludeOU8 -and $_.DistinguishedName -notmatch $excludeOU9 -and $_.DistinguishedName -notmatch $excludeOU10 -and 
      $_.DistinguishedName -notmatch $excludeOU11 -and $_.DistinguishedName -notmatch $excludeOU12 -and $_.DistinguishedName -notmatch $excludeOU13 }
}

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用正则表达式与notmatch一起使用。

[regex]$excluderegex = "^(excludeOU1|excludeOU2|excludeOU3)$"
(Get-ADForest).domains | foreach {
    Get-ADUser -filter {Enabled -eq $True} -properties * -SearchBase "OU=Accounts,$((Get-ADDomain -Server $_).DistinguishedName)" -Server $_ | 
    where-object {$_.Title -notmatch "Volunteer" -and $_.DistinguishedName -notmatch $excluderegex}
}

答案 1 :(得分:1)

您可以在Where过滤器表达式中放置任何您喜欢的内容:

$excludes = $excludeOU1,$excludeOU2,$excludeOU3,$excludeOU4,$excludeOU5,$excludeOU6,$excludeOU7,$excludeOU8,$excludeOU9,$excludeOU10,$excludeOU11,$excludeOU12,$excludeOU13
Get-ADUser -Filter {Enabled -eq $true} -Properties * -SearchBase "OU=Accounts,$((Get-ADDomain -Server $_).DistinguishedName)" -Server $_ | Where-Object {
    $_.Title -notmatch 'Volunteer' -and $(&{
        foreach($exclude in $excludes)
        {
            if($_.DistinguishedName -match $exclude)
            {
                return $false
            }
        }
        return $true
    })
}

答案 2 :(得分:0)

您可以使用管道中的 Select-Object cmdlet将新的“计算属性”添加到仅包含用户OU的 Get-ADUser 数据中。然后 Where-Object 调用可以简单地使用 -notin 运算符。

在我看来,这会使代码更具可读性。更多信息:

Select-Object Calculated Properties

Notin Operator