gpt4 book ai didi

powershell - Format-Table 根据输出缓冲区宽度设置列宽

转载 作者:行者123 更新时间:2023-12-03 23:00:47 27 4
gpt4 key购买 nike

我有一个使用 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
}
这适用于控制台输出,它产生如下输出:
a                                            b-                                            -AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBAAAAAAAAAAAA                                 BBBBBBBBBBBB

Problem

When I specify a different output buffer width, using the Width argument of Out-String or Out-File, the formatting won't change, it will still be based on the console buffer width.

Write-Something | Out-File test.txt -Width 200
这会产生与上面相同的输出,而预期的输出应该是宽度为 100 的列,不会发生换行。
如何获得由 Width 设置的实际输出缓冲区宽度 Out-String 的论据或 Out-File从我的 cmdlet 中?

最佳答案

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

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

关于powershell - Format-Table 根据输出缓冲区宽度设置列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65885176/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com