我有一个使用的 cmdletFormat-Table
输出可能很长的字符串(例如注册表路径)。我想将每列宽度设置为输出缓冲区宽度除以列数。
Example:
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 BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
AAAAAAAAAAAA BBBBBBBBBBBB
Problem
当我指定不同的输出缓冲区宽度时,使用Width
的论证Out-String
or Out-File
,格式不会改变,它仍然基于控制台缓冲区宽度。
Write-Something | Out-File test.txt -Width 200
这会产生与上面相同的输出,而预期输出应该是宽度为 100 的列,并且不会发生换行。
如何获得由设置的实际输出缓冲区宽度Width
的论证Out-String
or Out-File
从我的 cmdlet 中?
问题是您已经修复了 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)