Formatting and Output
Prerequisites: Selecting and sorting
PowerShell decides automatically how to display objects — as a table for
a few properties, as a list for many. The Format-* cmdlets let you
choose.
$user = [pscustomobject]@{ Name = 'Ada'; City = 'London'; Age = 36 }
$user | Format-Table
$user | Format-List
Name City Age
---- ---- ---
Ada London 36
Name : Ada
City : London
Age : 36
Format-Table— columns;-AutoSizefits them to the content.Format-List— one property per line, ideal for objects with many properties.Format-List *shows every property, including ones hidden by default.
Format last, and only for display
Format-* cmdlets turn objects into formatting instructions. After
formatting, the data is gone:
$formatted = [pscustomobject]@{ Name = 'Ada' } | Format-Table
$formatted[0].GetType().Name
FormatStartData
So Get-Process | Format-Table | Export-Csv produces a useless CSV of
formatting objects. Always put Format-* at the end of a pipeline, and
never in the middle of data processing.
Sending output elsewhere
| Cmdlet | Sends output to |
|---|---|
Out-File |
a text file (as it would appear on screen) |
Export-Csv |
a CSV file (data, not display) |
ConvertTo-Json |
JSON text |
Out-GridView |
an interactive window (Windows) |
Out-Null |
nowhere — discards output |
Write-Output vs Write-Host
function Get-Answer {
Write-Host "Calculating..."
Write-Output 42
}
$result = Get-Answer
"The result is $result"
Calculating...
The result is 42
Write-Output(or simply leaving a value on its own line) sends data down the pipeline — it's what a function returns.Write-Hostwrites directly to the screen and is not captured in$result. Use it only for display messages, never for data.