2016-12-30 13 views
1

は予めご容赦:PowerShellはどこオブジェクト内のコレクションを反復処理

を私はダースかそこらのOUを除外しながら、特定のOU内のユーザーのためのActive Directoryを照会するスクリプトを持っていますそのOU内。スクリプトは機能しますが、さまざまなOUを表す13の変数を宣言し、where-objectでそれらを参照すると、面倒です。私は複数のドメインを照会しているので、既存のforeachループもあります。私はすべてのOUを参照する方法を見つけたいのですが、どこのオブジェクトで13個の変数を参照することを避けるために、単一のコレクションまたは配列などのクエリから除外しています。誰かが私を正しい方向に向けることができますか?

(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 } 
} 

ありがとう: 既存のコード(コードは以下のOU変数defintionsを除きます)!

答えて

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

あなたは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 
    }) 
} 
0

あなたのに新しい「計算されたプロパティ」を追加して、あなたのパイプラインでを選択し、オブジェクトコマンドレットを使用することができますGet-ADUserユーザーのOUだけを保持するデータ。 Where-Objectコールでは、単に -notin演算子を使用できます。

私の意見では、これはコードを少し読みやすくします。詳細:

Select-Object Calculated Properties

Notin Operator

関連する問題