使用 Format-Table 控制列宽 [英] Controlling column widths with Format-Table

查看:39
本文介绍了使用 Format-Table 控制列宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从列表中获取某些 PC 的上次重新启动时间.当我使用

I am trying to get the last reboot time of some PCs from a list. When I use

foreach ($pc in $pclist) {
  Get-CimInstance -ClassName win32_operatingsystem -ComputerName $pc |
    select csname, lastbootuptime 
}

输出如下.

csname       lastbootuptime
------       --------------
CONFA7-L1-1A 7/15/2016 9:55:16 AM
CONFA7-L1-1F 5/31/2016 8:51:46 AM
CONFA7-L1-1G 6/18/2016 11:09:15 AM
CONFA7-L1... 6/26/2016 5:31:31 PM
CONFA7-L3... 7/24/2016 3:48:43 PM

这很整洁,但是如果PC名称很长,我就看不到全名.所以我流水线Format-Table:

Which is neat, but if the PC name is long, I am unable to see the full name. So I pipelined Format-Table:

Get-CimInstance -ClassName win32_operatingsystem -ComputerName $pc |
  select csname, lastbootuptime |
  Format-Table  -HideTableHeaders 

这就是我得到的:

CONFA7-L1-1A 7/15/2016 9:55:16 AM



CONFA7-L1-1E 7/21/2016 12:58:16 PM



CONFA7-L1-1F 5/31/2016 8:51:46 AM

这里有两个问题.

  1. 没有标题.如果我删除 -HideTableHeaders,每个不需要的输出都会有标题.

  1. There is no heading. If I remove -HideTableHeaders there will be heading for every output which is not required.

中间有很多空白.

基本上我只需要获得与第一个类似的输出,但不截断全名.我该如何解决这些问题?

Basically I just need to get an output similar to the first one, but without truncating the full names. How can I fix these?

推荐答案

总结和补充 PetSerAlAnsgar Wiechers:

tl;dr

Get-CimInstance -ClassName win32_operatingsystem -ComputerName $pclist |
  Sort-Object CSName |
    Format-Table CSName, LastBootUpTime -AutoSize

-AutoSize 可确保 CSName(计算机名称)列的宽度与一样宽,以显示其中的所有值full(除非这些值本身太长而不能放在一行中,在这种情况下必须使用 -Wrap - 见下文).

-AutoSize is what ensures that the CSName (computer name) column is as wide as it needs to be to show all values in full (unless these values themselves are too long to fit on a single line, in which case -Wrap must be used - see below).

Get-CimInstance 接受计算机名称的数组,因此不需要循环;然而,由于目标计算机并行被查询,返回的对象的顺序通常匹配计算机名称的输入顺序 - 这可以通过 Sort-Object CSName 调用.

Get-CimInstance takes an array of computer names, so there's no need for a loop; however, since the target computers are queried in parallel, the order of objects returned will typically not match the input order of computer names - this is rectified with the Sort-Object CSName call.

控制单个列的宽度:

To control the width of individual columns:

# Instead of a simple property name, 'prop1', pass a *hashtable*
# (@{ ... }`) with a 'width' entry to Format-Table
PS> [pscustomobject] @{ prop1='1234567890'; prop2='other' } |
       Format-Table -Property @{ e='prop1'; width = 5 }, prop2

prop1 prop2
----- -----
1234… other

注意:在 Windows PowerShell 中,您只会看到 12... 作为截断值,因为它使用 3 个单独的 . 字符表示截断;在 PowerShell [Core] 6+ 中,这被改进为使用 单个 字符,...(水平省略号,U+2026).

Note: In Windows PowerShell, you'll see just 12... as the truncated value, because it uses 3 individual . characters to represent the truncation; in PowerShell [Core] 6+ this was improved to using a single character, (HORIZONTAL ELLIPSIS, U+2026).

继续阅读以了解有关表格格式的更多信息.

本质上,您的问题是关于如何控制表格输出的输出列宽,这适用于任何 cmdlet 的输出.

At its core, your question is about how to control the output column width of tabular output, which applies to any cmdlet's output.

使用 Format-Table cmdlet(直接)用于表格输出,不是 Select-Object:Select-Object 的目的是创建自定义对象,而不是格式化输出;如果这些对象(通常是没有预定义格式视图的任何类型的实例)碰巧有 4 个或更少的属性,它们默认在幕后使用 Format-Table 进行格式化(但你不能应用选项);否则,隐式使用的是 Format-List.谢谢,PetSerAl.

Use the Format-Table cmdlet (directly) for tabular output, not Select-Object: the purpose of Select-Object is to create custom objects, not to format output; if such objects (generally, instances of any type without predefined formatting views) happen to haven 4 or fewer properties, they are by default formatted with Format-Table behind the scenes (but you don't get to apply options); otherwise, it is Format-List that is implicitly used. Thanks, PetSerAl.

  • Format-Table 总是将输出行限制为可用的屏幕宽度,这意味着:

  • Format-Table invariably limits output lines to the available screen width, which means:

  • 可能根本不会打印列.
  • 特别是打印的最后一列的值可能会被截断,缺失的部分由 .../... 表示 - 但请注意 all 打印的列可以具有截断值,如下所述.
  • Columns may not get printed at all.
  • Especially the last column that is printed may have its values truncated, with the missing part indicated by ... / - though note that all printed columns can have truncated values, as explained below.

如果你想创建更长的行,将Format-Table的输出通过管道传送到|Out-File -Width |Out-String -Stream -Width ;请注意,如果您将后者打印到屏幕上,则行将换行(但额外的换行符不会成为数据的一部分).

If you want to create longer lines, pipe Format-Table's output to | Out-File -Width <int> or | Out-String -Stream -Width <int>; note that if you print the latter to the screen, lines will wrap (but the extra line breaks won't be part of the data).

  • 警告:在 Windows PowerShell 上,不要使用 -Width ([int]::MaxValue),因为 table-具有格式化数据的类型的格式化数据无条件地用空格填充到全宽,这可能会消耗输出文件中过多的内存/空间,甚至可能会耗尽内存.在 PowerShell Core 中,此问题已在至少 v6.1 中得到修复.

  • Caveat: On Windows PowerShell, do NOT use -Width ([int]::MaxValue), because table-formatted data for types with formatting data is unconditionally right-padded with spaces to the full width, which can consume inordinate amounts of memory / space in the output file and you may even run out of memory. In PowerShell Core, this has been fixed as of at least v6.1.

Windows 上的替代方案(在 Unix 类平台上的 PowerShell Core 中不起作用)是使用 [console]::BufferWidth =<column-count> 加宽 屏幕缓冲区 以允许更长的行而不换行,但需要水平滚动.
此外,在 Windows 上,它仅适用于常规控制台,而不适用于 ISE.

An alternative on Windows (does not work in PowerShell Core on Unix-like platforms) is to use [console]::BufferWidth = <column-count> to widen the screen buffer to allow longer lines that don't wrap, but require horizontal scrolling.
Additionally, on Windows it only works in the regular console, not in the ISE.

控制列宽 - 这间接决定了适合多少列 - 使用以下参数:

To control column widths - which indirectly determines how many columns will fit - use the following parameters:

  • -AutoSize ... 告诉 Format-Table 使列尽可能宽以适合所有数据值,但请注意,这可能会导致显示的列更少(不太常见:更多).

  • -AutoSize ... tells Format-Table to make columns as wide as necessary to fit all data values, but note that this can result in fewer (less typically: more) columns getting displayed.

-Wrap ...使列值跨越多行,如果需要,以避免截断;同样,这适用于所有谢谢,zett42.,而不仅仅是最后一个,即在自动确定或固定的列宽(通过 width 条目指定,如下所示)碰巧超出特定值的情况下.

-Wrap ... makes column values span multiple lines, if needed, to avoid truncation; again, this can apply to all columnsThanks, zett42., not just the last one, namely in case an automatically determined or fixed column width (specified via a width entry, as shown next) happens to be exceeded by specific values.

指定自定义列宽,请将带有width条目的哈希表作为参数传递- 所谓的计算属性Format-Table-Property 参数;例如,以下示例将第 1 个输出列限制为 5 个字符:

To specify custom column widths, pass a hashtable with a width entry as an argument - a so-called calculated property to Format-Table's -Property parameter; e.g., the following example limits the 1st output column to 5 characters:

  [pscustomobject] @{ prop1='1234567890'; prop2='other' } |
    Format-Table -Property @{ e='prop1'; width = 5 }, prop2

  • 如果发生截断,默认应用于值的末尾,截断指示符 .../...总是占用截断值的 最后 3 个字符(在 Windows PowerShell 中)/仅占 last 个字符(在 PowerShell [Core] 6+);在上面的示例中,prop1 值呈现为 12.../1234... 总共 5 个字符.

    • If truncation occurs, which is applied to the end of values by default, the truncation indicator ... / invariably takes up the last 3 characters of the truncated value (in Windows PowerShell) / only the last character (in PowerShell [Core] 6+); in the example above, the prop1 value renders as 12... / 1234… for a total of 5 chars.

      要截断值的开始,您必须将列更改为对齐,并带有 alignment = 'right' 条目(默认为 'left''center' 是第三个选项;这两个选项都会截断值的 end).

      To truncate the start of values instead, you must change the column to be right-aligned, with a alignment = 'right' entry (default is 'left', 'center' is the 3rd option; both of these truncate the end of values).

      如果您想保留 对齐同时仍然在值的 开始 截断,则必须在脚本块中使用自定义表达式 ({ ... }) 分配给 e (expression) 条目:

      If you want to retain left alignment while still truncating at the start of values, you'll have to use a custom expression in a script block ({ ... }) assigned to the e (expression) entry:

      [pscustomobject] @{ prop1='1234567890'; prop2='other' } |
        Format-Table -Property @{ 
            n='prop1'; e={ $_.prop1 -replace '^.+(.{4})$', '…$1'}; width = 5 
          }, prop2
      

    • 注意:指定至少一个自定义宽度意味着您必须在 -Property 参数中明确枚举要输出的所有属性,甚至那些不需要自定义宽度的.[1]

    • Note: Specifying at least one custom width means that you must explicitly enumerate all properties to output in the -Property argument, even the ones that don't need custom widths.[1]

      注意事项,自 PowerShell 7.1 起:

      • bug 阻止自定义宽度生效,除非 第一 列(也)有一个;此外,它永远最后列中生效 - 请参阅GitHub 问题 #14676.

      • A bug prevents custom widths from taking effect unless the first column (also) has one; additionally, it never takes effect in the last column - see GitHub issue #14676.

      正如 zett42这个答案如果第一列是指定自定义宽度的计算列,则剩余的线宽均匀分布em> 在那些本身没有指定列宽的剩余列中,无论这些列中的值实际有多宽 - 除非您还通过 -AutoSize>.GitHub 问题 #14677 中讨论了这种意外行为.

      As zett42 points out and demonstrates in this answer, if the first column is a calculated one that specifies a custom width, the remaining line width is evenly distributed among those remaining columns that do not themselves specify a column width, irrespective of how wide the values in those columns actually are - unless you also pass -AutoSize. This unexpected behavior is discussed in GitHub issue #14677.

      [1] 正如 zett42 指出的那样,如果所有列都可以在技术上绕过此要求将具有相同的自定义宽度,因为将属性名称字符串传递给 e (Expression) 哈希表条目被解释为 通配符模式,以便字符串 '*' 匹配 所有 属性名称;例如:
      [pscustomobject] @{ a=1;b=2 } |格式表@{ e='*';宽度=10 }

      [1] As zett42 points out, you can technically bypass this requirement if all columns are to have the same custom width, because passing a property-name string to the e (Expression) hashtable entry is interpreted as a wildcard pattern, so that string '*' matches all property names; e.g.:
      [pscustomobject] @{ a=1; b=2 } | Format-Table @{ e='*'; width=10 }

      这篇关于使用 Format-Table 控制列宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆