如何用PowerShell将ArrayList分组统计结果转置为列格式?
Transpose Group-Object Results to Horizontal Format for Excel Export
No worries, this is a common ask when working with grouped data in PowerShell. The default vertical output from Group-Object is great for reading, but when you need it horizontal for Excel, we just need to restructure the data a bit.
Here's a step-by-step solution that will give you exactly the format you want:
# Your original list $list = "letter","solo","nap","nap","nap","sharp","ignite","tap","tap","tap","tap","evoke" # Group the items and get Name/Count pairs $groupedItems = $list | Group-Object | Select-Object Name, Count # Build an ordered hashtable to keep items in their original first-occurrence order $horizontalData = [ordered]@{} foreach ($item in $groupedItems) { $horizontalData[$item.Name] = $item.Count } # Convert the hashtable to a custom object for clean horizontal output $finalResult = [PSCustomObject]$horizontalData # Preview the result in PowerShell $finalResult # Export to a CSV file (Excel will open this perfectly) $finalResult | Export-Csv -Path "ItemCounts.csv" -NoTypeInformation # Optional: If you have the ImportExcel module installed, export directly to Excel with formatting # Install-Module -Name ImportExcel -Scope CurrentUser -Force # $finalResult | Export-Excel -Path "ItemCounts.xlsx" -AutoSize -BoldTopRow
What this does:
- Grouping: We start by grouping your list items just like you did before, getting the name of each item and its count.
- Ordered Hashtable: Using
[ordered]ensures the columns in the final output stay in the same order as the items first appeared in your list (so "letter" comes first, then "solo", etc.—matching your desired format). - Custom Object: Converting the hashtable to a
PSCustomObjecttransforms the vertical groups into a single horizontal row of data, which is exactly what Excel expects.
When you run $finalResult in PowerShell, you'll see this output:
letter solo nap sharp ignite tap evoke ------ ---- --- ----- ------ --- ----- 1 1 3 1 1 4 1
And when you open the exported CSV or Excel file, the structure will be identical—item names as column headers, counts as the first row of values.
内容的提问来源于stack exchange,提问作者Jamie_lee
相关产品推荐
相关产品推荐

