2017-04-26 53 views
1

這裏是我的腳本:多重比較操作輸出錯誤結果的PowerShell

#set the root search path 
$rootPath = "c:\test\path\" 

#get a list of all directories and subdirectories in the root path 
$shares = Get-ChildItem -Path $rootPath -Directory 

#create empty array to store custom properties later 
$obj = @() 

#for every folder you find..... 
foreach ($share in $shares) { 

    #finds all security principals for each share on fileserver that has permissions explicitly assigned 
    $notInherited = Get-Acl -Path $share.FullName | select -ExpandProperty Access | Where-Object {$_.IsInherited -eq $false} 

    #for every security principal that has explicit permissions assigned.... 
    foreach ($member in $notInherited) { 

     #extract the identity of the resource from the IdentityReference field and convert it to a string object 
     [string]$identity = $member.IdentityReference 

     #test to see if the extracted resource contains a \ anywhere in the name to ensure we're looking for domain objects 
     if ($identity -like '*\*') { 

     #retrieve the SAM of the resource by splitting the string object at the \ and returning the 1 field 
     $samAccountName = $identity.Split('\')[1] 

      #filter out all domain related groups like domain admins, domain users, domain controllers, domain computers 
      if ($samAccountName -notlike 'Domain*' -or $samAccountName -notlike 'Administrators') { 

       #return AD object info for the resource using it's SAM 
       $ADObject = Get-ADObject -Filter ('SamAccountName -eq "{0}"' -f $SamAccountName) 

       #test to ensure we're only retrieving groups and not users who are explicitly assigned 
       if ($ADObject.ObjectClass -eq 'group') { 

        #create a PS object and append it's properties to the empty array created earlier 
        #assign custom fields to the object (FolderName maps to the share name and GroupName maps to name of group that has access to the share) 
        $obj += [pscustomobject] @{ 
        'GroupName' = $ADObject.Name 
        'FolderName' = $share.Name 
        } 
       } 
      } 
     } 
    } 
} 

#output the contents of the object to the console 
Write-Output $obj | ft -AutoSize | out-file C:\Scripts\test02.txt 

我不知道爲什麼這條線會產生錯誤的結果:

if ($samAccountName -notlike 'Domain*' -or $samAccountName -notlike 'Administrators') 

我期望的輸出不包括任何文件夾「管理員」或任何以「域」開頭的組明確添加。如果我刪除後半部分進行測試,以便僅檢查「域*」,則輸出是正確的。我也需要過濾掉管理員組。我錯過了什麼?

+5

嘗試-and代替-or'如果($的samAccountName -notlike「域*」 - 和$的samAccountName - 不喜歡'管理員')' –

+0

哈哈在我的部分失敗。我可以發誓我做了 - 第一次,它沒有工作......無論如何,這解決了我的問題。謝謝。! –

回答

1

你的要求:

if ($samAccountName -notlike 'Domain*' -or $samAccountName notlike 'Administrators') 

字面翻譯爲 「不喜歡X」 或 「不喜歡Y」

我覺得你想找的是:

if (!($samAccountName -like 'Domain*' -or $samAccountName -like 'Administrators')) 

{直寫主機「是」}

這樣,如果$ samAccountName類似於'Domain *'或$ samAccountName````Administrato rs',它返回TRUE,然後!將其轉換爲假。

因此,如果滿足任一條件,結果爲false,並且代碼塊不運行。因此,如果用戶是一個域*或者用戶是管理員,也不會輸出「是」 ..