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

时间:2018-12-08 12:24:38

标签: windows powershell powershell-v6.0

我尝试了各种方式来格式化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 个答案:

答案 0 :(得分:3)

PowerShell通常返回对象,并将其字符串表示形式输出到主机。您希望将自定义字符串格式输出到主机。您可以通过多种方式来实现,但是最快的方法和我的建议是使用import * as THREE from 'three'; operator

-f

使用$OS = Get-CimInstance Win32_OperatingSystem '{0} ({1}) {2} [{3}]' -f $OS.Caption, $OS.Version, $OS.OSArchitecture, $OS.InstallDate 可以对多行​​进行相同操作。

here-strings

但是,您应该尽可能地使用-尽可能多的对象。

答案 1 :(得分:1)

我相信这应该对您有用:

$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"))]"

答案 2 :(得分:0)

只需使用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 *
相关问题