How to column print only certain row parts of a list in powershell?

4.8k Views Asked by At

I have tried various ways to format the output from a poweshell command and would like to print only some of the row items in the list as part of a a column in one line.

Perhaps more easy to illustrate:

# 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]

How can this be easily accomplished?

(Coincidentally I want all the rows in this case, but a more general answer may be more useful, if it also include rows that we don't want.)

3

There are 3 best solutions below

1
On BEST ANSWER

PowerShell usually returns objects and outputs a string representation of it to the host. You want a custom string format output to the host. You can achieve that in various ways, however the fastest way and my recommendation would be to use the -f operator.

$OS = Get-CimInstance Win32_OperatingSystem

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

With here-strings use can do the same with multi-line.

$OS = Get-CimInstance Win32_OperatingSystem

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

However, you should work with objects as much as - and as long as it is possible.

2
On

I would belive this should work for you:

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

The Select-Object makes sure that you get the desired properties. Having a variable with all the details in it, we can concatenate it like this:

"$($temp.Caption) ($($temp.version)) $($temp.OSArchitecture) [$($temp.InstallDate.ToString("yyyy-MM-dd hh:mm:ss"))]"
0
On

Simply use Format-Table instead of Format-List. They both support a list of properties you want to see. So if you don't want all columns, list the ones you want.

# '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 *