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>
CodePudding user response:
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.