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

PowerShell 7.4.5中Format-Wide如何保留ANSI文件颜色格式?

解决PowerShell中Format-Wide丢失目录高亮的问题

核心原因

Format-Wide 默认仅输出 FileInfo/DirectoryInfo 对象的 Name 属性纯文本,不会保留 $PSStyle.FileInfo 定义的样式信息,导致颜色高亮失效。

解决方案

方法1:临时使用计算属性直接应用样式

这是最快捷的临时方案,直接在 Format-Wide 中通过计算属性手动注入样式:

Get-ChildItem | Format-Wide -Property @{
    Name = 'StyledName'
    Expression = { $PSStyle.FileInfo[$_.Mode] + $_.Name + $PSStyle.Reset }
} -Column 4
  • $PSStyle.FileInfo[$_.Mode]:根据文件/目录的模式(如d代表目录)自动匹配预设样式
  • $PSStyle.Reset:重置样式,避免后续输出被当前颜色影响
  • 可修改 -Column 参数调整列数

方法2:自定义函数封装(适合长期使用)

写一个自定义函数替代原生的 Format-Wide 调用,方便重复使用:

function gciw {
    param(
        [int]$Column = 4,
        [Parameter(ValueFromPipeline)]
        [System.IO.FileSystemInfo[]]$InputObject,
        [string[]]$Path = '.'
    )

    begin { $items = @() }
    process { $items += $InputObject }
    end {
        if (-not $items) { $items = Get-ChildItem -Path $Path }
        $items | ForEach-Object {
            $PSStyle.FileInfo[$_.Mode] + $_.Name + $PSStyle.Reset
        } | Format-Wide -Column $Column
    }
}

使用方式:

  • 直接调用:gciw -Column 3
  • 管道传入:Get-ChildItem C:\ | gciw

方法3:修改默认格式文件(永久生效)

通过修改PowerShell的格式定义文件,让Format-Wide默认保留样式:

  1. 导出默认的FileInfo格式定义:
Get-FormatData System.IO.FileInfo, System.IO.DirectoryInfo | 
    Export-FormatData -Path "$HOME\Documents\PowerShell\CustomFileSystem.Format.ps1xml"
  1. 打开导出的XML文件,找到<View>节点中ViewName="WideView"的部分,将原有的<TableColumnItem>替换为:
<TableColumnItem>
    <ScriptBlock>$PSStyle.FileInfo[$_.Mode] + $_.Name + $PSStyle.Reset</ScriptBlock>
</TableColumnItem>
  1. 导入修改后的格式文件(可加入PowerShell配置文件$PROFILE实现自动加载):
Update-FormatData -PrependPath "$HOME\Documents\PowerShell\CustomFileSystem.Format.ps1xml"

内容的提问来源于stack exchange,提问作者star

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 10:27:09