如何在不截断值的情况下使用 Format-Table?

How do I use Format-Table without truncation of values?

我目前有一个脚本可以 ping 服务器并检查每台服务器上的服务 运行 的状态。

我使用 Out-File 保存输出,但 PowerShell 在长字符串后放置省略号或“...”。我不希望它这样做。例如:

MachineName  ServiceName             Status StartType
-----------  -----------             ------ ---------
SrvGtw01     Test.MyService....       Running  

我希望它显示全名,例如:

MachineName  ServiceName              Status StartType
-----------  -----------              ------ ---------
SrvGtw01     Test.MyServiceName.Here  Stopped  Disabled

我一直在读到您可以将 $FormatEnumerationLimit 首选项变量设置为 -1,我已经尝试过了,但它不起作用。我不确定我应该如何将它放在我的脚本中。

$FormatEnumerationLimit 首选项变量在这里不适用,因为它的目的是确定 collection-valued 中有多少个元素 属性 显示(例如,$FormatEnumerationLimit = 2; [pscustomobject] @{ prop = 1, 2, 3 } 打印(最多)来自 .prop 值的 2 个元素,并提示 ... 存在更多元素;例如,{1, 2...}).

相反,您必须:

  • (a) 确保个别列不会在显示时截断它们的值

    • 首先通过管道传输到 Format-Table -Autosize
  • (b) 确保整体输出宽度可以适合所有列:

    • 管道到 Out-File -Width 具有足够大的值(但是不要使用 [int]::MaxValue,因为表格的每一行输出被填充到那个宽度[1]) .

    • 警告: 如果您没有明确设置 -Width - 如果您刚刚使用 >,例如 - 当前控制台 window 的宽度被使用 - 不管它是什么.

例如:

# Assumes that the objects in $results only contain the properties
# of interest (MachineName, ServiceName, Status, StartType); you 
# can also pass an explicit list of output properties to Format-Table, however.
$results | Format-Table -AutoSize | Out-File -Width 512 C:\log.txt -Append

注意:要在控制台中预览输出 - 这可能涉及 line-wrapping - 使用
Out-String -Width 512 相反。


[1] 在 PowerShell Core 中,这个不需要的 last-column 填充已被删除,至少从 v6.1.0 开始。