我有一个 cmdlet,用于Format-Table输出可能很长的字符串(例如注册表路径)。我想将每列宽度设置为输出缓冲区宽度除以列数。
例子:
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
}
Run Code Online (Sandbox Code Playgroud)
这对于控制台输出非常有效,它会产生如下输出:
ab - - 啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 啊啊啊啊啊啊啊啊啊啊啊啊
当我使用或Width参数指定不同的输出缓冲区宽度时,格式不会改变,它仍然基于控制台缓冲区宽度。Out-StringOut-File
Write-Something | Out-File test.txt -Width 200
Run Code Online (Sandbox Code Playgroud)
这会产生与上面相同的输出,而预期输出应该是宽度为 100 的列,并且不会发生换行。
如何获取由 cmdlet或cmdlet 中的Width参数设置的实际输出缓冲区宽度?Out-StringOut-File
问题是您已经修复了 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2633 次 |
| 最近记录: |