1

I want to make use of Format-Table to neatly format some properties. This works fine, but once I've called Format-Table on an object, I'm unable to access any of the properties for future use.

$VersionInfo = Get-ComputerInfo -Property "*version"
$VersionInfo.OsVersion

Output:

10.0.19042
$VersionInfoFT = Get-ComputerInfo -Property "*version" | Format-Table
$VersionInfoFT.OsVersion

Output:

<empty>
smholvoet
  • 327
  • 5
  • 15
  • 4
    `Format-*` are for **display purposes only**. If you actually want to process data further, you should leave that out – Theo Mar 26 '22 at 10:59
  • 2
    If you want to work with the data later. Try for something like array of custom objects or array of hashtables. – Walter Mitty Mar 26 '22 at 11:01
  • 2
    Additional background info to complement Theo's comment and zett42's answer: `Format-*` cmdlets output objects whose sole purpose is to provide _formatting instructions_ to PowerShell's output-formatting system. In short: only ever use `Format-*` cmdlets to format data _for display_, never for subsequent _programmatic processing_ - see [this answer](https://stackoverflow.com/a/55174715/45375) for more information. – mklement0 Mar 26 '22 at 18:21

1 Answers1

2

As commenters wrote, the Format-* cmdlets are for display purposes only. They output formatting instructions which produce richly formatted output only when it ends up in the console or at another "end point" (i. e. any of the Out-* cmdlets). These instructions generally can't be used to get back to the original data.

You normally keep the unformatted objects in a variable for further processing:

$VersionInfo = Get-ComputerInfo -Property "*version"
$VersionInfo.OsVersion

Now you can store the formatting data in another variable as you did before ($VersionInfoFT = $VersionInfo | Format-Table), but it usually doesn't make much sense. Typically you either output formatted information immediately or convert it to string.

# Format and output only the OsVersion property
$VersionInfo | Format-Table OsVersion

# Format and convert to string with indentation 
$VersionInfoStr = ($VersionInfo | Format-List | Out-String -Stream) -join "`n    "
Write-Verbose "All version info:$VersionInfoStr"

In the last example it makes sense to store the formatted output as string, to reduce the complexity of the Write-Verbose call. This is done by piping to the Out-String cmdlet which basically produces the same output as you see in the console, as a string. The -Stream argument is used to split the resulting string into separate lines, so we can rejoin them to produce indented output.

zett42
  • 25,437
  • 3
  • 35
  • 72