You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:

  1. Grouping: We start by grouping your list items just like you did before, getting the name of each item and its count.
  2. 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).
  3. Custom Object: Converting the hashtable to a PSCustomObject transforms 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:12:53