2016-01-06 55 views
0

我需要檢測不是至少一個組的成員的計算機對象。我已經提出了這個腳本,但不是隻列出至少一個組的成員的機器,而是返回所有工作站。我究竟做錯了什麼?檢測計算機是否不是至少一個組的成員

Get-ADComputer -Filter * -Property * | where { 
    $_.memberof -notmatch 'Group1' -and 
    $_.memberof -notmatch 'Group2' -and 
    $_.memberof -notmatch 'Group3' 
} | Format-Table Name 

回答

1

MemberOf屬性包含可分辨名稱的列表。您無法檢查它是否包含-notmatch運算符的內容。相反,讓您的組的可分辨名稱的列表:

$groups = 'Group1', 'Group2', 'Group3' | 
      ForEach-Object { Get-ADGroup -Filter "Name -eq '$_'" } | 
      Select-Object -Expand DistinguishedName 

,並檢查MemberOf屬性不包含任何人:

Get-ADComputer -Filter * -Property * | Where-Object { 
    -not (Compare-Object $groups $_.MemberOf -IncludeEqual -ExcludeDifferent) 
} | Format-Table Name 

Compare-Object是必需的,因爲你需要檢查如果一個數組包含另一個數組的任何元素。像$_.MemberOf | Where-Object {$groups -contains $_}也可以工作。

注意,MemberOf屬性確實包括計算機的主要組。如果主組也不能是從列表中的羣體之一,你需要在Where-Object過濾器的額外檢查:

Get-ADComputer -Filter * -Property * | Where-Object { 
    -not (Compare-Object $groups $_.MemberOf -IncludeEqual -ExcludeDifferent) -and 
    $groups -notcontains $_.PrimaryGroup 
} | Format-Table Name 
+0

我必須說,這是一個更好的答案。我會用這個,OP。 – FoxDeploy

+0

謝謝Ansgar,這個作品完美! – zimmerkm

0

您使用的是-NotMatch運算符,它的值爲true,如果該項目不完全匹配。你會使用-NotContain得到更好的服務,像這樣

Get-ADComputer -Filter * -Property * | where {$.memberof -notContains 'Group1' -and $.memberof -notContains 'Group2' -and $_.memberof -notContains 'Group3'} | Format-Table Name 
+0

'MemberOf'包含可分辨名稱的列表。檢查組別名稱列表是否包含組名稱將始終返回'$ false'。 –

相關問題