Write-Host

Write a string to the display, optionally customizing the output. Output can be to any host but is typically the console screen.

Syntax
      Write-Host [[-object] Object] [-noNewLine] [-separator Object]
             [-foregroundcolor ConsoleColor] [-backgroundColor ConsoleColor]
                [CommonParameters]

Key
   -object Object
       Object to display, typically a string.
        
   -noNewLine 
       Do not end with a newline character.
        
   -separator
       String to output between objects displayed on the console.

   -foregroundcolor ConsoleColor
       The text color

   -backgroundcolor ConsoleColor
       Background color

   ConsoleColors:
       Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow,
       Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White

Starting in PowerShell 5.0, Write-Host also acts as a wrapper for Write-Information. You can now use Write-Host to emit output to the information stream, but the $InformationPreference preference variable and InformationAction common parameters do not affect Write-Host messages.

So in effect Write-Host is always set to Continue and will always display, unless stream 6 is redirected.

Standard PowerShell output will trim/wrap output lines to match the width of the parent console window -1
Write-Host bypasses this step and writes directly to stdout.

Write-host by default adds a single space separator between items, to remove that you must specify an empty string '' as the separator.

Examples

Output a message:

PS C:\> Write-Host "Hello World 123" -foregroundcolor green

Output a message & variable value:

PS C:\> Write-Host "message" $variable -foregroundcolor red

If stream 6 is redirected to Null there is no output:

PS C:\> Write-Host "Hello World 123" 6>$null

Run a function to display some text:

PS C:\> Function Test-function { Write-host "here is some text" }
PS C:\> Test-function
here is some text

If we assign the function to a variable, the function runs and the text is displayed, it is not absorbed by the pipeline:

$result = Test-function

Display text in specific colours:

PS C:\> write-host "The quick brown fox jumped" -foregroundcolor DarkGreen -backgroundcolor white

PS C:\> Write-Host -ForeGroundColor Red "some text in red" -nonewline

Display several variables concatenated together with no separation character:

PS C:\> write-host $one $two -separator ''
firstsecond

“In our life there is a single color, as on an artist's palette, which provides the meaning of life and art. It is the color of love” ~ Marc Chagall

Related PowerShell Cmdlets

Clear-Host - Clear the screen.
Out-Host - Send output to the host.
Write-Debug - Write a debug message to the host display.
Write-Information - Write to the information data stream (6).
Write-Output - Write an object to the pipeline.
Write-Warning - Write a warning message.


 
Copyright © 1999-2024 SS64.com
Some rights reserved