powershell - 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-String
Out-File
Write-Something | Out-File test.txt -Width 200
这会产生与上面相同的输出,而预期的输出应该是宽度为 100 的列,并且不会发生换行。
如何获取由我的 cmdlet 的参数设置的实际输出缓冲区宽度Width
?Out-String
Out-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
推荐阅读
- javascript - 在 vanilla js 应用程序中使用 redux
- optimistic-locking - Optimistic concurrency control and write skew
- java - 以xml格式保存数据
- xml - Roku 中的导航概念
- spring-boot - javax.el.PropertyNotFoundException:目标无法访问,标识符 [MyController] 使用 Spring Boot 和 JSF 解析为 null
- java - 如何使用服务帐户凭据将文件上传到 Google Team Drive 中的文件夹?
- java - Java - 调用方法
- java - 如何从 Windows 连接远程 Q 管理器(在 docker 上)?
- java - 无法在 log4j2 中使用 RollingFileAppender 写入日志
- scala - 函数定义中的“简单表达式的非法开始”