Active-Directory

如何在 PowerShell 中查找 Windows 安全組的所有成員,分配給變數名並輸出到 CSV?

  • December 8, 2021

我本身不是 sysAdmin/PowerShell 人,但無法讓這個 Powershell 查詢正常工作。

需要撤回特定 Windows 安全組中的所有使用者並以特定方式對其進行格式化(如下所示),但是在確定我的安全組過濾器不起作用的原因時遇到了一些問題,並且想知道我的方式是否有問題設置過濾器。

#Snippet
$searcher.filter = "(&(memberof=CN=My Windows Security Group,OU=SecurityGroups,OU=Messaging,OU=Enterprise,DC=****,DC=****)(objectCategory=*))"
$results = $searcher.findall()

我在 PowerShell ISE 中設置了一個斷點,但是 $results 在調試時不包含任何值。

我從一位同事的現有腳本中對此進行了建模,看起來他正在查詢 DL,並且在調試時看到了 $results 值:

#---------------------------------------------------------
#DL Filter Example (works)
#---------------------------------------------------------
$Searcher.Filter = "(&(memberOf=CN=DL_TestApp_Admin,OU=Distribution Lists,OU=Messaging,OU=Enterprise,DC=dcInfo,DC=dcInfo,DC=****)(objectCategory=*))"
$results = $searcher.findall()

這是過濾 Windows 安全組的整個 PS 腳本(由我修改)

$curdate = (Get-Date).ToString("MMddyyyy")

$baseDN = "LDAP://"
$Searcher = New-Object DirectoryServices.DirectorySearcher
$searcher.searchroot = new-object system.directoryservices.directoryentry($basedn)
#---------------------------------------------------------
#Windows Security Group Filter (doesn't work)
#---------------------------------------------------------
$searcher.filter = "(&(memberof=CN=My Windows Security Group,OU=SecurityGroups,OU=Messaging,OU=Enterprise,DC=****,DC=****)(objectCategory=*))"
$results = $searcher.findall()

   #---------------------------------------------------------
   #Build the dataset in specific format
   #---------------------------------------------------------
   $usercsv = $results | #-Object {
        New-Object -TypeName PSObject -Property @{
           "User ID" = $_.properties['samAccountName'][0]
           "User Role" = "Blah"
           "Elevated Role" = "Y"
           "Internal User" = "Y"
           "Date of Last Login" = $null
           "App Specific Info 1" = $null
           "App Specific Info 2" = $null
           "Account Creation Date" = $null
           "Last Password Change Date" = $null
           "User Email Address" = $_.properties['mail'][0]
           "User First Name" = $null
           "User Last Name" = $null
           "App Specific Info 3" = $null
           "Review Group" = $null
       }
   }

#export to csv
$usercsv | Select-Object -Property "User ID","User Role","Elevated Role","Internal User","Date of Last Login","App Specific Info 1","App Specific Info 2","Account Creation Date","Last Password Change Date","User Email Address","User First Name","User Last Name","App Specific Info 3","Review Group" | Export-Csv -NoTypeInformation  -Path "UsersListing_$curdate.csv"

Write-Host "Wrote", $results.Count, "record(s)"

#removing last CR LF
#TODO: Move this to a common function in a separate script for all     
scripts to call
$stream = [IO.File]::OpenWrite("UsersListing_$curdate.csv")
$stream.SetLength($stream.Length - 2)
$stream.Close()
$stream.Dispose()

最初,我將其編寫為在 DevOps Poweshell 發布管道中執行,如下所示以生成 csv 文件:

$Members = Get-ADGroup -Filter {Name -eq "WSG"} -Properties Member | 
Select-Object -ExpandProperty Member

$GlobalCatalog = "$((Get-ADDomainController -Discover).Name):xxxx"

$output = Foreach ($User in $Members)
{
 Get-ADUser -Identity $User -Server $GlobalCatalog -Properties CN,    
 EmailAddress, AccountExpirationDate, Created, HomePage, LastLogonDate, 
 PasswordLastSet, whenCreated | Select-Object CN, 
 SamAccountName,EmailAddress, AccountExpirationDate, Created, Enabled,     
 HomePage, LastLogonDate, Name, PasswordLastSet, UserPrincipalName, 
 whenCreated 
}

#output csv file
$output | Export-Csv $Env:TEMP\Users.csv -NoTypeInformation

在這種情況下,輸出格式無關緊要,我不確定是否可以修改此查詢以將結果輸出為以下格式:

           "User ID" = $_.properties['samAccountName'][0]
           "User Role" = "Blah"
           "Elevated Role" = "Y"
           "Internal User" = "Y"
           "Date of Last Login" = $null
           "App Specific Info 1" = $null
           "App Specific Info 2" = $null
           "Account Creation Date" = $null
           "Last Password Change Date" = $null
           "User Email Address" = $_.properties['mail'][0]
           "User First Name" = $null
           "User Last Name" = $null
           "App Specific Info 3" = $null
           "Review Group" = $null

此查詢的結果採用以下特定格式:

CN                    : 
SamAccountName        : 
EmailAddress          : 
AccountExpirationDate : 
Created               : 
Enabled               : 
HomePage              : 
LastLogonDate         : 
Name                  : 
PasswordLastSet       : 
UserPrincipalName     : 
whenCreated           : 

提前感謝您的任何幫助。

這是為獲得我們所追求的結果而開發的最終 Poweshell:

$curdate = (Get-Date).ToString("MMddyyyy")
#-------------------------------------------------------------------------------
# Get members for Windows Security Groups
#-------------------------------------------------------------------------------
$Members = Get-ADGroup -Filter {Name -eq "My AD Group"} -Properties Member | Select-Object -ExpandProperty Member

$GlobalCatalog = "$((Get-ADDomainController -Discover).Name):1234"
$results = @()

Foreach ($User in $Members)
{    
   $userInfo = Get-ADUser -Identity $User -Server $GlobalCatalog  -Properties SamAccountName, EmailAddress, LastLogonDate
   $details = [ordered] @{
       
       "Active Directory ID"           = $userInfo.SamAccountName
       "User Role"                     = "My AD Group"
       "Elevated Role"                 = "N"
       "Internal User"                 = "Y"
       "Date of Last Logon"            = $userInfo.LastLogonDate
       "Application Specific Info 1"   = $null
       "Application Specific Info 2"   = $null
       "Acct Creation Date"            = $null
       "Last PWD Change Date"          = $null
       "User Email Address"            = $userInfo.EmailAddress
       "User First Name"               = $null
       "User Last Name"                = $null
       "Application Specific Info 3"   = $null
       "Review Group"                  = $null

   }
   $results = New-Object PSObject -Property $details
}
#---------------------------------------------------------
#output results to csv
#---------------------------------------------------------
$results | Export-Csv -NoTypeInformation  -Path "UsersListing_$curdate.csv"

變數名稱(Active Directory ID、使用者角色等)代表 CSV 文件中的列標題。

希望它可以幫助某人。

由於Windows Server 2008 R2 中引入了Active Directory PowerShell 模組,因此無需擔心實際的 LDAP 搜尋。

Get-ADGroupMember是您正在尋找的。如果您隨後需要有關組成員的更多詳細資訊,您可以在他們上使用Get-ADUser來獲取您需要的任何資訊。

AD PowerShell 模組會自動安裝在所有域控制器上,但您可以通過啟用相應的 Windows 功能將其安裝在任何 Windows Server 系統上:

Install-WindowsFeature RSAT-AD-PowerShell

您還可以將它作為遠端伺服器管理工具的一部分安裝在 Windows 客戶端系統上。

引用自:https://serverfault.com/questions/1081300