Input, Output, and Streams
Prerequisites: Script parameters, Formatting and output
PowerShell has several output streams. Keeping them separate means data stays clean while messages still reach the user.
| Stream | Written with | Used for |
|---|---|---|
| Success (1) | Write-Output or a bare value |
data — what a script returns |
| Error (2) | Write-Error, exceptions |
errors |
| Warning (3) | Write-Warning |
potential problems |
| Verbose (4) | Write-Verbose |
detailed progress (hidden by default) |
| Debug (5) | Write-Debug |
debugging detail (hidden by default) |
| Information (6) | Write-Information, Write-Host |
messages for the user |
function Get-Total {
[CmdletBinding()]
param([int[]]$Numbers)
Write-Verbose "Adding $($Numbers.Count) numbers"
if ($Numbers -contains 0) { Write-Warning 'The list contains a zero' }
($Numbers | Measure-Object -Sum).Sum
}
$total = Get-Total -Numbers 5, 0, 10
"Total: $total"
$total = Get-Total -Numbers 1, 2 -Verbose
"Total: $total"
WARNING: The list contains a zero
Total: 15
VERBOSE: Adding 2 numbers
Total: 3
- Only the sum went into
$total; the warning and verbose messages went to their own streams, displayed on screen but not mixed into the data. Write-Verbosemessages appear only with-Verbose— perfect for detail people only want when troubleshooting. ([CmdletBinding()]gives a function the-Verboseswitch — see Advanced Functions in Level 2.)
Redirecting streams
# illustrative
.\script.ps1 > output.txt # success stream to a file
.\script.ps1 2> errors.txt # errors to a file
.\script.ps1 *> all.txt # every stream to a file
.\script.ps1 3> $null # discard warnings
Asking the user
# illustrative
$name = Read-Host 'What is your name'
$password = Read-Host 'Password' -AsSecureString
Read-Host waits for input; -AsSecureString hides it. For scripts that
run unattended, take parameters instead of prompting.