如何用PowerShell将AD组名与用户数分别写入CSV的不同单元格?
Fixing CSV Output for Active Directory Group User Counts
Let's sort out that CSV formatting issue you're having! The core problem with your current code is that you're treating CSV like plain text—using Add-Content or string concatenation doesn't respect the column structure CSV needs. Instead, we need to create structured objects in PowerShell, then let Export-Csv handle the formatting correctly.
Here's a robust, clean solution that will put group names and user counts in separate cells:
# Adjust these paths to match your files $inputFilePath = "C:\path\to\your\groups.csv" # Assumes CSV with column 'adgroupname' $outputFilePath = "C:\path\to\your\group_counts.csv" # Initialize an array to store our results $groupResults = @() # Read the group list (use Get-Content instead if your input is a plain text file) $groupList = Import-Csv -Path $inputFilePath foreach ($groupEntry in $groupList) { $groupName = $groupEntry.adgroupname.Trim() try { # Get group members and count them $groupMembers = Get-ADGroupMember -Identity $groupName -ErrorAction Stop $memberCount = $groupMembers.Count # Create a custom object with our two columns $result = [PSCustomObject]@{ "AD Group Name" = $groupName "User Count" = $memberCount } # Add the object to our results array $groupResults += $result # Optional: Print progress to the console Write-Host "Successfully counted $memberCount users in group: $groupName" } catch { # Handle errors (e.g., group doesn't exist, permission issues) Write-Warning "Failed to process group '$groupName': $($_.Exception.Message)" # Add error entry to results so you don't miss problematic groups $errorResult = [PSCustomObject]@{ "AD Group Name" = $groupName "User Count" = "Error: $($_.Exception.Message)" } $groupResults += $errorResult } } # Export the structured results to CSV $groupResults | Export-Csv -Path $outputFilePath -NoTypeInformation -Encoding UTF8 Write-Host "Export completed! Results saved to: $outputFilePath"
Why this works better than your original code:
- Structured objects: By creating
[PSCustomObject]with explicit properties,Export-Csvknows exactly which values go into which columns—no more merged cells. - Error handling: The
try/catchblock ensures your script doesn't crash if a group is missing or you don't have permissions to access it. - Efficiency: Collecting results in an array and exporting once is faster than appending to the file line-by-line with
Add-Content, especially for large group lists.
If your input is a plain text file (one group per line):
Replace the Import-Csv line with:
$groupList = Get-Content -Path $inputFilePath
And adjust the loop to use $groupName directly:
foreach ($groupName in $groupList) { $groupName = $groupName.Trim() # Rest of the try/catch logic stays the same }
Key notes:
- The
-NoTypeInformationswitch removes the extra type header line thatExport-Csvadds by default, making your CSV cleaner. - Using
-Encoding UTF8ensures special characters in group names are handled correctly.
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

