约 1881 字

约 9 分钟

#格式化输出

PowerShell 默认会根据对象的类型自动选择显示格式。使用 Format-* 命令可以控制表格、列表和宽列表的显示方式。格式化命令只影响显示,不改变数据本身。

#Format-Table 表格输出

指定要显示的属性和列:

> Get-Process | Format-Table -Property ProcessName, Id, CPU

#-AutoSize

自动调整列宽,使内容尽量完整显示:

> Get-Process | Format-Table -Property ProcessName, Id, CPU -AutoSize

#-Wrap

内容过长时换行显示,而不是截断:

> Get-Process | Format-Table -Property ProcessName, Path -Wrap

#-GroupBy

按属性分组显示:

> Get-Service | Format-Table -Property Name, Status -GroupBy Status

-GroupBy 会为每个分组生成一个标题,适合查看分类数据。

#Format-List 列表输出

每个对象的属性逐行显示,适合属性较多或内容较长的情况:

> Get-Process | Format-List -Property ProcessName, Id, CPU

也可以显示全部属性:

> Get-Process | Format-List *

#Format-Wide 宽列表输出

将指定属性以多列方式排列:

> Get-ChildItem | Format-Wide -Property Name -Column 3

-Column 控制列数。单列形式适合生成简单的名称列表:

> Get-ChildItem | Format-Wide -Property Name -Column 1

#Out-String 转换为字符串

Out-String 将格式化后的输出转换为字符串:

> Get-Process | Format-Table -Property ProcessName, Id | Out-String

转换后的字符串可以保存、拼接或按行处理:

> $text = Get-ChildItem | Format-Table -Property Name, Length | Out-String
> $text.Length

#注意事项

  • 需要后续逻辑处理时,应先使用 Select-Object、Sort-Object 等命令,最后再格式化。
  • 默认输出已经会使用合适的格式,只有需要调整显示效果时才显式使用 Format-*。
  • Out-String 适合需要文本结果的场景,但会丢失对象的属性结构。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2