2016-05-16 70 views
0

我不確定我的邏輯關閉的位置?這個腳本背後的想法是查找與禁用的用戶帳戶關聯的所有管理員帳戶。我們使用SamAccountName的代碼,但管理員帳戶以我們的IT管理員的-a,-d,-e結尾。我想,如果我查看了所有禁用的用戶並創建了陣列,然後抓取了所有啓用的管理員帳戶,然後執行了前9個數字匹配的查找,我將列出具有啓用的管理員帳戶的禁用用戶列表。相反,我在兩個帳戶都禁用了匹配項,只有通過Excel才能看到具有關聯的已啓用管理員帳戶的匹配項。爲什麼我的方法不按我的意圖工作? THXPowershell包含鍵邏輯失敗Get-ADUser

$Users1 = Get-ADUser -Filter {enabled -eq $False} -Properties SamAccountName, name, title, enabled,lastlogondate,accountexpirationdate | select SamAccountName, name, title,enabled,lastlogondate, accountexpirationdate 
$Users2 = Get-ADUser -Filter {samaccountname -like "*-a" -or samaccountname -like "*-d" -or samaccountname -like "*-e" -and enabled -eq $True} -Properties SamAccountName, name, title,enabled, lastlogondate,accountexpirationdate | select SamAccountName, name,enabled, title,lastlogondate, accountexpirationdate 
$output = "C:\scripts\adcleanup\Admin-Accounts-Need-Term_$((Get-Date).ToString('MM-dd-yyyy')).csv" 
$SIDTable = @{} 

$Users1 | ForEach-Object { 

    $SIDTable[$_.SamAccountName] = $_ 
} 

$matching = ForEach ($User in $Users2) { 

    $SID = $User.SamAccountName.Substring(0,8) 

    If ($SIDTable.containskey($SID)) { 

    $SIDTable[$SID] | Select @{Name="SID";Expression={$user.SamAccountName}},SamAccountName,@{Name="Admin Enabled";Expression={$user.enabled}},"Enabled","Name", "Title", "LastLogonDate", "AccountExpirationDate" 

    }} 
    $matching | Export-csv $output -NoTypeInformation 
+0

'$字符串=子串(0,8)'會給你'$的第一** ** 8個字符string'。除非您確定samaccountname是* always * 8或9個字符,否則您寧願刪除最後一個'-a'(或'-d' /'-e'):'$ string.Remove($ string.IndexOf(' - '))' –

+0

我想這就是爲什麼我很困惑。我知道SamAccountNames的長度總是9個字符,所以我想我會得到正確的列表。就像你說的那樣,即使使用indexOf,當一個數組只能禁用而另一個數組僅禁用時,如何在禁用的帳戶上獲得包含密鑰? – MarcGel

回答

1

確保您組中的Filter正確的條款:

-Filter {(samaccountname -like "*-a" -or samaccountname -like "*-d" -or samaccountname -like "*-e") -and enabled -eq $True} 
+0

感謝Mathias。現在它正在工作。 – MarcGel