首页 > 解决方案 > Format-Table 根据输出缓冲区宽度设置列宽

问题描述

我有一个Format-Table用于输出可能很长的字符串(例如注册表路径)的 cmdlet。我想将每列宽度设置为输出缓冲区宽度除以列数。

例子:

function Write-Something {
    [CmdletBinding()] param()

    $o = [pscustomobject]@{ a = 'A' * 100; b = 'B' * 100 }
    
    $columnWidth = [int]( $PSCmdlet.Host.UI.RawUI.BufferSize.Width / 2 )
    $o | Format-Table @{ e = 'a'; width = $columnWidth }, @{ e = 'b'; width = $columnWidth } -wrap
}

这适用于控制台输出,它会产生如下输出:

抗体
- -
啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
AAAAAAAAAAAA BBBBBBBBBBBB

问题

当我使用or的Width参数指定不同的输出缓冲区宽度时,格式不会改变,它仍将基于控制台缓冲区宽度。Out-StringOut-File

Write-Something | Out-File test.txt -Width 200

这会产生与上面相同的输出,而预期的输出应该是宽度为 100 的列,并且不会发生换行。

如何获取由我的 cmdlet 的参数设置的实际输出缓冲区宽度WidthOut-StringOut-File

标签: powershell

解决方案


问题是您已经在 Write-Something cmdlet 中修复了宽度。执行此操作的 PowerShell 方法是让您的 cmdlet 输出未格式化的数据对象,并用您自己的控制输出宽度的 cmdlet 替换 Out-File。

function Write-Something {
    [CmdletBinding()] param()

    $o = [pscustomobject]@{ a = 'A' * 100; b = 'B' * 100 }
    Write-Output $o
}

function Out-Something {
    [CmdletBinding()] param(
        [Parameter(ValueFromPipeline=$true)]
        [psobject]$InputObject,
        [Parameter(Position=1)]
        [String]$FilePath,
        [Parameter(Position=2)]
        [int]$Width
    )

    $columnWidth = [int]( $Width / 2 )
    $InputObject | Format-Table @{ e = 'a'; width = $columnWidth }, @{ e = 'b'; width = $columnWidth } -Wrap | ` 
        Out-File -FilePath $FilePath -Width $Width
}

Write-Something | Out-Something test.txt -Width 200

推荐阅读