PowerShell has several ways to write data and messages to the console. You can use the Write-Host, Write-Output, Write-Information, or [console]::WriteLine commands. How do we use these commands to output data to the PowerShell console and what is the difference between them?
Open the PowerShell console and run the following commands one by one:
write-host "testing console output" write-output "testing console output"
At first glance, both commands are used to print text strings to the PowerShell console. Although Write-Output and Write-Host seemed to achieve the same result, they actually work quite differently.
- Write-Host writes a text string to console itself;
- Write-Object sends the text as a PowerShell object to the next command in the pipeline.
An analog of the echo command from the command line interpreter (cmd.exe) is the Write-Host cmdlet. Just pass whatever you want to be displayed in the console as the Write-Host argument.
The peculiarity of Write-Host is that it is the only cmdlet that allows you to manually change the background and foreground colors in the PowerShell console using -BackgroundColor and -Foregroundcolor keywords. The following color values are available:
Write-Host "Dark red background with White text" -BackgroundColor DarkRed -ForegroundColor White
With the -NoNewline option, you can prevent a space or newline character from being added after the Write-Host output.
Write-Host "first line with no new line option" -NoNewline; Write-Host "second string"
The -Separator option allows you to add a separator string or character to insert between objects printed to the console.
Write-Host (2,4,6,8,10,12) -Separator ", -> "
The Write-Output cmdlet sends the specified object down the pipeline to the next command. If the command is the last command in the pipeline, the object is displayed in the console.
Note. In PowerShell, the echo command is an alias for Write-Output.
Please note that a line with spaces is treated as several separate values and is displayed line by line. If you put the data in quotes, they will be interpreted as a single string value.
This cmdlet is commonly used in scripts to display strings and other objects on the console. However, since the default behavior is to display objects at the end of the pipeline, there is usually no need to use the cmdlet. For example, the results of the following two commands will be equivalent:
Get-Process | Write-Output
Thus, the main feature of the Write-Output cmdlet is that in most cases this command doesn’t need to be specified explicitly in your scripts.
You can suppress Write-Output by redirecting to $null:
Write-Output 'This line will not be shown' > $null
Write-Output 'This line will not be shown' | Out-Null
PowerShell cmdlets are used for debugging purposes or to show the result of any command or script in the user console.