PowerShell Write-Host Command Tutorial

PowerShell provides the Write-Host command or cmdlet in order to print given data into the screen or standard output. The standard output is generally the PowerShell command-line interface. The Write-Host command uses the ToString() method in order to convert a given data type into a string implicitly. By using the Write-Host command the output command style can be changed like foreground color or background color etc.

Write To The Console or PowerShell Command Line Interface

We will start with a simple example where we will use the Write-Host command in order to print console or with other name PowerShell Command Line Interface. The data we want to print can be specified as a value or variable as different types like String, Integer etc.

PS> Write-Host "Hello WindowsTect"
PS> $Message = "Hello WindowsTect"
PS> Write-Host $Message

The output is like below.

Write without New Line

By default, the Write-Host command adds a new line at the end of the output. This end of the line is generally useful as it provides readability to the output. But we can disable or remove this end of the line with the -NoNewline attribute. This will print output without a new line.

Write-Host "First Line"

Write-Host -NoNewline "Hello WindowsTect"

$Message = "Hello WindowsTect"
Write-Host -NoNewline $Message

The output will be like below.

First LineHello WindowsTectHello WindowsTect

Write Using Separator

The Write-Host command also provides the -Separator attribute which is used to put specified characters or separator to the output items. The Write-Host command can output sequencial types.

Write-Host (2,3,4,5,6,7) -Separator ", +1= "

2, +1= 3, +1= 4, +1= 5, +1= 6, +1= 7

Write with Specified Text and Background Color

One of the powerful features of the Write-Host is changing the text or foreground and background colors. The -ForegroundColor attribute is used to set foreground color and -BackgroundColor attribute is used to set background color.

Write-Host -BackgroundColor Red "Hello WindowsTect"

Write-Host -ForegroundColor Green "Hello WindowsTect"

Write-Host -BackgroundColor Yellow -ForegroundColor Green "Hello WindowsTect"
Write with Specified Text and Background Color

Leave a Comment