代码之家  ›  专栏  ›  技术社区  ›  not2qubit

如何在powershell中仅列打印列表的某些行部分?

  •  0
  • not2qubit  · 技术社区  · 7 年前

    我尝试了各种方法来格式化poweshell命令的输出,并且只想将列表中的一些行项目作为列的一部分打印在一行中。

    也许更容易说明:

    # I want the output from:
    Get-CimInstance Win32_OperatingSystem | select Caption,Version,OSArchitecture,InstallDate | fl
    
    Caption        : Microsoft HAL 9000
    Version        : 6.3.9000
    OSArchitecture : 64-bit
    InstallDate    : 2018-08-16 00:50:01
    
    # To look like this:
    Microsoft HAL 9000 (6.3.9000) 64-bit  [2018-08-16 00:50:01]
    

    这怎么容易做到呢?

    3 回复  |  直到 7 年前
        1
  •  3
  •   vrdse    7 年前

    PowerShell通常会返回对象并向主机输出其字符串表示形式。您希望将自定义字符串格式输出到主机。您可以通过各种方式实现这一点,但是最快的方式和我的建议是使用 -f operator .

    $OS = Get-CimInstance Win32_OperatingSystem
    
    '{0} ({1}) {2} [{3}]' -f $OS.Caption, $OS.Version, $OS.OSArchitecture, $OS.InstallDate
    

    here-strings 使用多行可以执行相同的操作。

    $OS = Get-CimInstance Win32_OperatingSystem
    
    @'
    My OS is {0} {1})
    Architecture --> {2}
    Installation Date: [{3}]
    '@ -f $OS.Caption, $OS.Version, $OS.OSArchitecture, $OS.InstallDate
    

        2
  •  1
  •   Mötz    7 年前

    我相信这会对你有用:

    $temp = (Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, OSArchitecture,InstallDate)
    

    选择对象可确保获得所需的特性。有了一个包含所有细节的变量,我们可以像这样连接它:

    "$($temp.Caption) ($($temp.version)) $($temp.OSArchitecture) [$($temp.InstallDate.ToString("yyyy-MM-dd hh:mm:ss"))]"
    
        3
  •  1
  •   user2226112 user2226112    7 年前

    Format-Table 而不是 Format-List

    # 'default' properties in a table
    Get-CimInstance Win32_OperatingSystem | ft
    
    # only some properties in a table
    Get-CimInstance Win32_OperatingSystem | ft Caption, OSArchitecture
    
    # without table headers
    Get-CimInstance Win32_OperatingSystem | ft Caption, OSArchitecture -HideTableHeaders
    
    # all properties in a list (because there are too many for a table)
    Get-CimInstance Win32_OperatingSystem | fl *
    
    推荐文章