我正在學習PowerShell,並期待查詢AD組的幾個並確定用戶是否是AD組的成員。簡化PowerShell查詢
- 1部分:查詢,其具有10個嵌套AD組
- 部2a AD組:查詢用戶的AD組和拉列表
- 3部分:不貼,但比較第1部分的輸出和第2部分
在線搜索,發現一些山雀和位。我知道Active Directory模塊,但不要使用它,因爲此腳本將由非技術用戶執行,並避免僅爲此安裝RSAT。
我有Powershell的版本2和Windows 7
第1部分
組1是具有10個嵌套AD組的廣告羣組。
Write-Host "Fetching information from groups.Please wait.."
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$group=[System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity ($ct,'group1')
$group1 = $group.GetMembers | Where {$_.StructuralObjectClass -eq "group"} | Select SamAccountName
$group1 = $group1 -replace("=", " ") -replace("{", " ") -replace("@", " ") -replace ("}", " ") -replace("SamAccountname", " ") -replace '\s+', ' '
$ADGroups = foreach ($l in group1) {$l.trim()}
以確保廣告組信息由節目提取或退出腳本,其中文件可以被寫入
$location = "C:\AD"
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
If ($user -like $null) {
Write-host "User does not exist in AD" -foreground "magenta"
start-sleep 10
break
}
Write-Host "Please wait...Looking user group membership..."
$usergroups = $user.GetGroups()
卸下文件
if (($ADgroups | out-string) -like $null) {
Write-Host "Unable to fetch AD groups information" -foreground "red"
Start-sleep 10
break
}
第2部分
溫度位置如果存在。
Remove-Item $location\useradgroups.txt
$usergroups | select SamAccountName | Out-File $location\useradgroups.txt -append
$testr = gc $location\useradgroups.txt
if (($testr | out-string) -like $null) {
Write-Host "Unable to fetch user AD groups information" -foreground "red"
Start-sleep 10
Remove-Item $location\useradgroups.txt
break
}
$useradgroups = foreach ($l in $testr) {$l.trim()}
$useradgroups | Select-String -Pattern "\w" | out-file $location\useradgroups.txt
$useradgroups = gc $location\useradgroups.txt
問:
除非我調整輸出,無法進行比較。所以不得不寫的腳本如上圖所示:
- 避免書面方式輸出到文本文件
- 避免
-replace("=", " ") -replace("{", " ")
在第1部分 - 簡化代碼。
任何來自Powershell大師的建議都會受到歡迎。它會幫助我學習過程
感謝您的回覆。我試圖獲取嵌套在GROUP1下的10個AD組。如果用戶是任何10個嵌套組的成員,則應顯示其所屬組的成員名稱和用戶名。因此,例如,如果Bob是嵌套在GROUP1下的GROUP A的成員,它應該顯示「Bob是A組的成員」。明天早上我會嘗試你的解決方案。 – Kevin
感謝BoblobLaw。您提供給查詢Group1的腳本工作並顯示所有組成員,並顯示所有組成員的可分辨名稱作爲輸出。 $ user變量是用戶的登錄ID。所以如果我輸入我的loginid/samaccountname,它應該提取我的用戶組信息並與Part1輸出進行比較。 – Kevin