Home PowerShell How To Use PowerShell Write Host Command

How To Use PowerShell Write Host Command [Step-By-Step]

There is a lot of jargon and terminology in the computing world. Sometimes it becomes a bit tricky knowing what to use, keep or throw away. With PowerShell, the PowerShell write host command is one that you may not be sure of.

Straight out of my heart I would tell you, that using this command will depend on your needs – You may or may not ever need to use it.

The article will help inform your decision on using this command. You will understand the PowerShell Write-Host and know when it must be used.

Without further ado, let us jump right into it!

How to Use the Modern PowerShell Write Host Command

Emphasis on the word “modern”. The reason is before PowerShell 5.x, With PowerShell write host was a bit different. It had no links to stream (such as error, success, or warning). This meant the use of this command was a little bit discouraged, mainly because you did not have as much control in relation to other output types.

It is not uncommon in Powershell scripts for information to be passed down to a user. This information may not directly relate to the script’s output, but it is still informational.

I will show with a small example, a command that dishes information to a user with regards to the processing time of a script.

Write-Host “Let us gather some important information now. Be patient, it will take a minute!”
Write-Host “- Gathering Process`r`n- Gathering Files`r`n- Gathering Users”
Write-Output “This is a place holder for the information”
Write-Host “Now the Information Gathering has been completed!”

powershell write host

If you take a close look at the command that was run and the final executed script, you will see that it simply serves the purpose of outputting some information to the host. In this example, the host happens to be the end-user of the script.

The bigger question would be if it is possible to display information when you send sending objects between different functions or cmdlet. The answer is YES! PowerShell’s Write Host function has no effect on the pipeline output. Below is an example of how this works.

Function Get-Information {
    Write-Host “Let us gather some important information now. Be patient, it will take a          minute!`r`n”
    Write-Host “- Gathering Data`r`n- Returning Data`r`n”

       [PSCustomObject]@{
      “Test1” = “Value1”
      “Test2” = “Value2”
}
 
   Write-Host “Information Gathering Complete!”
   }
 
     Function Convert-Information {
      Param(
      [Parameter(ValueFromPipeline=$true)]$Param
     )
 
  $Param | ConvertTo-JSON
  }

It is possible to pipe a Get-Information output to Convert-Information. Doing this means is ceases to take into cognizance the different statements and will only act upon the PSCustomObject that is rendered as output.

How to Format Messages to Make Them More Readable

A message can be plain or beautifully presented. PowerShell write host is capable of letting users format their messages, adding color to the output. Doing this helps in increasing the readability. It will help anyone using the script understand better the actions to take.

Here are a few format options to keep in mind:

  1. BackgroundColor: This is the color of what you have behind the text.
  2. ForegroundColor: This refers to the color of the text itself.
  3. NoNewLine: This simply commands the computer not to show a new line after the command is executed.
  4. Separator: This is a good way to show word or character separators that are not the regular space used by Write-Host. This may refer to a newline character or any carriage return.

Next, I would like to show you all the options you would be able to harness in constructing a beautifully formatted message.

I will be creating an informational message using an array for the number of results. In this example, I would apply some formatting to make it pop a bit more.

Note: It is possible to pass several objects in a With PowerShell Write Host command just as is displayed below. Ideally, there would be a need to have a scripter to create a separation in these messages, but using the separator parameter, it is possible to control how the output shows up on the console.

$Array = @(5,6,7,8,9)

Write-Host “Count Results:” -BackgroundColor DarkBlue -ForegroundColor White -NoNewline
Write-Host “” $Array.Count “Items`r`n” -ForegroundColor Red
Write-Host $Array -Separator “`r`n”
Write-Host “” “End of results.” -ForegroundColor Green -Separator “`r`n”

powershell write host

By performing a format as we have in the above example, the user now has more useful information about the script to work with. One use case would be if an informational menu needs to be created. There are of course many other use cases.

How to Redirect Output from PowerShell Write Host Stream

There are a number of methods for controlling and diverting the output now that With PowerShell Write Host may be controlled by stream output. With PowerShell Write Host messages, the InformationAction choice is partially taken into consideration.

Although the -InformationAction Ignore option successfully suppresses Write-Host messages, the $InformationPreference and the InformationAction parameters have no impact on the Write-Host cmdlet.

Write-Host is nothing more than a wrapper for the Write-Information function. This allows Write-output Hosts to be included in the information stream. This implies you can use the information stream to change where Write-Host messages travel.

However, you may still use the redirection operators to send the output of Write-Host messages to a separate stream. Write every Write-Host message to a log file, for example. Let’s use the same example as before and redirect all of the output to a log file.

Write-Host “Counting Results:” -BackgroundColor DarkBlue -ForegroundColor White -NoNewline 6>> .\logfile.txt
Write-Host “” $Array.Count “Items`r`n” -ForegroundColor Yellow 6>> .\logfile.txt
Write-Host $Array -Separator “`r`n” 6>> .\log.txt
Write-Host “” “Results End Here.” -ForegroundColor Red -Separator “`r`n” 6>> .\logfile.txt

How To Use PowerShell Write Host Command [Step-By-Step]

PowerShell now routes the result to a log, as you’ve seen, although the style may not be precisely what you wanted. Because the -NoNewLine option is mainly used as a host styling tool, it isn’t actually honored. This isn’t a major problem, but it’s something to consider when diverting the stream output.

What is Powershell

If you have read this far, you must have an understanding of PowerShell. but I would like to round up with a quick sum-up of the tool where you can execute the With PowerShell write host command we have discussed.

PowerShell is a task automation system that consists of a console or command-line shell, scripting or programming language, and a configuration management structure that works across platforms. PowerShell is compatible with Linux, Windows, and macOS.

PowerShell is a contemporary command shell that combines the finest aspects of existing common command shells. PowerShell takes and returns.NET objects, unlike other shells that recognize and return text. These features are included in the shell:

  • Command-line history that is robust
  • Command prediction and Tab completion
  • Script and parameter aliases are supported
  • The in-console help system, comparable to the Unix man pages
You may like to read our guide on PowerShell vs Command Prompt: Getting Started with Windows PowerShell.

Language for scripting

PowerShell is a language for scripting that is widely used to automate system management and administration. It’s also utilized in CI/CD setups to create, test, and deliver solutions. The.NET Common Language Runtime underpins PowerShell (CLR).

.NET objects are used for all inputs and outputs. There usually will not be a need to parse text output for the purpose of getting information out of it. The following are some of the characteristics of the PowerShell scripting language:

  • Functions, scripts, classes, and modules make it extensible.
  • Formatting method with a lot of flexibility for simple output
  • Dynamic type system with an extensible type system
  • Support for standard data formats such as JSON, CSV, and XML is built-in.

📗FAQ📗

What does Write-host in PowerShell do?

In PowerShell, Write-Host is a cmdlet that writes to the console. It is typically used to display messages or output to the user and is often used for debugging purposes.

The Write-Host cmdlet allows you to specify the text to be displayed, as well as the foreground and background colors of the text.

Here is an example of how you might use Write-Host in a script:

Write-Host “Hello, World!”

The console will display the message “Hello, World!”.

You can also use the -ForegroundColor and -BackgroundColor parameters to specify the colors of the text and background, respectively.

For example:

Write-Host “Hello, World!” -ForegroundColor Green -BackgroundColor Black

This will display the message “Hello, World!” in green text on a black background.

What is the difference between Write-host and Write-output in PowerShell?

In PowerShell, Write-Output is a cmdlet that sends its output to the pipeline. This means that the output of the cmdlet can be passed as input to another cmdlet or used as the value of a variable.

Write-Host, on the other hand, is a cmdlet that writes directly to the console. Its output is not passed to the pipeline, and it cannot be captured or redirected like the output of Write-Output.

Here is an example of how you might use Write-Output in a script:

$output = Write-Output “Hello, World!”

This will assign the string “Hello, World!” to the $output variable. The string can then be passed as input to another cmdlet or used in a script.

In general, Write-Output is preferred over Write-Host because it allows you to capture and manipulate the output in your scripts, whereas Write-Host is mainly used for displaying messages to the user.

However, there may be situations where Write-Host is more appropriate, such as when you want to display a message to the user and do not need to capture or manipulate the output.

Is Write-host same as Echo?

In PowerShell, Write-Host is similar to the echo command in other command-line environments. Both commands are used to display messages or output to the user.

The main difference between Write-Host and echo is that Write-Host is a cmdlet in PowerShell, while echo is a command in other command-line environments, such as the Windows Command Prompt or the Bash shell on Linux.

Here is an example of how you might use echo in a script:

echo “Hello, World!”

The console will display the message “Hello, World!”.

In PowerShell, you can also use the echo alias for Write-Output, which will send the output to the pipeline. For example:

$output = echo “Hello, World!”

This will assign the string “Hello, World!” to the $output variable, and the string can then be passed as input to another cmdlet or used in a script.

Should I use Write-host?

In general, it is generally better to use Write-Output instead of Write-Host in PowerShell scripts. This is because Write-Output allows you to capture and manipulate the output in your scripts, while Write-Host is mainly used for displaying messages to the user.

However, there may be situations where Write-Host is more appropriate, such as when you want to display a message to the user and do not need to capture or manipulate the output. In these cases, Write-Host can be a useful tool for providing feedback to the user or for debugging purposes.

It is also worth noting that Write-Host has a few other features that can be useful in certain situations. For example, you can use the -NoNewline parameter to prevent a new line from being added after the output, or you can use the -ForegroundColor and -BackgroundColor parameters to specify the colors of the text and background, respectively.

In summary, whether or not to use Write-Host in a script depends on your specific needs and the context in which you are using it. If you need to capture or manipulate the output, Write-Output is usually the better choice. If you just want to display a message to the user, Write-Host can be a useful tool.

Why do hackers use PowerShell?

There are several reasons why hackers might use PowerShell in their attacks.

1. To start with, PowerShell is a strong tool that can be used to automate and control a variety of Windows operating system functions. This means that operations that would normally take a long time or be challenging to complete manually may now be carried out by hackers on a compromised system using PowerShell.

2. Second, PowerShell is readily accessible and doesn’t need any additional software to be installed because it is included in the majority of current Windows editions. It is therefore a practical option for hackers who wish to sneakily access a target system.

3. Third, PowerShell supports scripts, which can be used to automate complicated activities or carry out tasks that would be challenging to execute manually. This makes it a handy tool for hackers who wish to automate their attacks or who wish to develop unique tools in order to accomplish their goals.

Finally, there are a few security features in PowerShell that can be disregarded or taken advantage of by hackers.

Using encoded or obfuscated scripts, for instance, can make it challenging for security tools to identify malicious activities. PowerShell’s execution policy can also be circumvented to allow unsigned scripts to run.

How do I connect to a host in PowerShell?

To connect to a host in PowerShell, you can use the Enter-PSSession cmdlet. This cmdlet allows you to establish a remote connection to a computer and run commands on that computer as if you were sitting in front of it.

Here is an example of how you might use Enter-PSSession to connect to a remote host:

Enter-PSSession -ComputerName HOSTNAME

Replace HOSTNAME with the name or IP address of the host you want to connect to.

You can also specify a user name and password to use for the connection by using the -Credential parameter. For example:

Enter-PSSession -ComputerName HOSTNAME -Credential (Get-Credential)

This will prompt you to enter a user name and password to use for the connection.

Once you are connected to the host, you can run commands on the remote computer as if you were logged in to it locally. To exit the remote session and return to your local computer, use the Exit-PSSession cmdlet.

Exit-PSSession

What is Write-output in PowerShell?

In PowerShell, Write-Output is a cmdlet that sends its output to the pipeline. This means that the output of the cmdlet can be passed as input to another cmdlet or used as the value of a variable.

Here is an example of how you might use Write-Output in a script:

$output = Write-Output “Hello, World!”

This will assign the string “Hello, World!” to the $output variable. The string can then be passed as input to another cmdlet or used in a script.

You can also use Write-Output to send the output of a command or script to the pipeline. For example:

Get-Process | Write-Output

This will display a list of all the processes running on the system, and the output can be passed to another cmdlet or used in a script.

In general, Write-Output is preferred over the Write-Host cmdlet because it allows you to capture and manipulate the output in your scripts, while Write-Host is mainly used for displaying messages to the user.

What does $_ mean in PowerShell?

In PowerShell, $_ is a special variable that represents the current object in the pipeline. It can be used in scripts and commands to refer to the object that is being processed at that time.

For example, consider the following script:

Get-Process | ForEach-Object {
Write-Output “$($_.Name) is running on the system.”
}

This script will get a list of all the processes running on the system, and for each process it will output a message that includes the name of the process. The $_ variable is used to refer to the current process object being processed in the pipeline, and the Name property of the object is used to get the name of the process.

$_ can be used in many different contexts in PowerShell, including in script blocks, loops, and filters. It is a powerful and versatile tool that can be used to simplify and streamline your scripts and commands.

How do I write a PowerShell output to a file?

To write the output of a PowerShell command or script to a file, you can use the Out-File cmdlet. This cmdlet allows you to send the output of a command to a file, rather than displaying it in the console.

Here is an example of how you might use Out-File to write the output of a command to a file:

Get-Process | Out-File C:\processes.txt

This will create a file named processes.txt in the root of the C: drive, and it will contain a list of all the processes running on the system.

You can also use the -Append parameter to add the output to the end of an existing file, rather than overwriting the file. For example:

Get-Process | Out-File C:\processes.txt -Append

This will add the list of processes to the end of the processes.txt file, rather than overwriting the file.

You can also use the -Encoding parameter to specify the encoding when writing the file. For example:

Get-Process | Out-File C:\processes.txt -Encoding ASCII

This will write the file using ASCII encoding.

Overall, Out-File is a useful cmdlet that allows you to save the output of PowerShell commands and scripts to a file, which can be useful for storing the results of your work or sharing the output with others.

How do I write output to console in PowerShell?

To write output to the console in PowerShell, you can use the Write-Output cmdlet. This cmdlet sends its output to the pipeline, which means that the output will be displayed in the console by default.

Here is an example of how you might use Write-Output to write output to the console:

Write-Output “Hello, World!”

This will display the message “Hello, World!” in the console.

You can also use Write-Output to send the output of a command or script to the console. For example:

Get-Process | Write-Output

This will display a list of all the processes running on the system.

You can also use the Write-Host cmdlet to write output to the console. This cmdlet is similar to Write-Output, but it writes directly to the console and does not send its output to the pipeline.

Write-Host “Hello, World!”

Overall, Write-Output and Write-Host are both useful cmdlets for writing output to the console in PowerShell.

Write-Output is generally preferred because it allows you to capture and manipulate the output in your scripts, while Write-Host is mainly used for displaying messages to the user.

Can we use echo in PowerShell?

Yes, you can use the echo command in PowerShell to display a message or the value of a variable. Here is an example of using echo to display a message:

PS C:> echo “Hello, World!”
Hello, World!

And here is an example of using echo to display the value of a variable:

PS C:> $message = “Hello, World!”
PS C:> echo $message
Hello, World!

You can also use the Write-Output cmdlet to achieve the same result as echo. For example:

PS C:> Write-Output “Hello, World!”
Hello, World!

Should I use echo or printf?

In PowerShell, you should use the echo or Write-Output cmdlets instead of printf. printf is not a built-in cmdlet in PowerShell and it is not commonly used.

What are 3 drawbacks of PowerShell?

1. One drawback of PowerShell is that it is only available on Windows operating systems, so it cannot be used on other platforms such as Linux or macOS.

2. Another drawback is that PowerShell scripts can be difficult to read and understand if they are not well-documented or organized. This can make it challenging for other users, particularly those who are not familiar with PowerShell, to modify or maintain the scripts.

3. A third drawback is that PowerShell does not have as many built-in cmdlets as some other scripting languages, so it may not be as well-suited for certain tasks.

For example, if you need to perform a complex operation that requires a large number of steps, it might be more efficient to use a language like Python that has a larger standard library.

What is :$ false in PowerShell?

In PowerShell, the :$ operator is used to define a variable as a boolean value ($true or $false).

PowerShell write-host vs write-output

The Write-Host and Write-Output cmdlets are both used to display output in PowerShell, but they have some key differences.

Write-Host is used to display output directly to the console, and it does not return any output to the pipeline. This means that the output of Write-Host cannot be captured or redirected. Write-Host is typically used to display messages to the user, such as prompts or warning messages.

Write-Output, on the other hand, sends the output to the pipeline, where it can be captured or redirected to a file or another cmdlet. Write-Output is generally used for program output, rather than messages to the user.

Here is an example of using Write-Host to display a message to the user:

PS C:> Write-Host “This is a message to the user.”
This is a message to the user.

And here is an example of using Write-Output to display the same message:

PS C:> Write-Output “This is a message to the user.”
This is a message to the user.

In this example, both Write-Host and Write-Output will display the message on the console. However, only Write-Output will send the output to the pipeline, where it can be captured or redirected.

It is generally recommended to use Write-Output for program output, and to reserve Write-Host for messages to the user. This helps to ensure that the output of your scripts can be easily captured and redirected, as needed.

PowerShell write-host double quotes

In PowerShell, you can use double quotes (") to enclose strings that contain spaces or special characters. When you use double quotes, PowerShell will interpret variables and escape sequences within the string.

Here is an example of using double quotes to enclose a string that contains a variable:

PS C:> $message = “Hello, World!”
PS C:> Write-Host “The message is: $message”
The message is: Hello, World!

In this example, the Write-Host cmdlet is used to display a string that contains the $message variable. The double quotes allow the value of the $message variable to be interpreted and included in the output.

You can also use double quotes to enclose strings that contain escape sequences. Escape sequences are special characters that are used to represent non-printable characters or to insert special characters into a string. For example, the escape sequence \n represents a newline, and the escape sequence \t represents a tab.

Here is an example of using double quotes and escape sequences to format a string:

PS C:> Write-Host “This is a string with a newline.\nThis is the second line.”
This is a string with a newline.
This is the second line.

In this example, the \n escape sequence is used to insert a newline between the two lines of text.

It is important to note that you must use double quotes, rather than single quotes ('), to enclose strings that contain escape sequences or variables. Single quotes will treat the contents of the string literally, and will not interpret escape sequences or variables.

PowerShell write host examples

Here are a few examples of using the Write-Host cmdlet to display output in PowerShell:

Example 1: Display a simple message:

PS C:> Write-Host “Hello, World!”
Hello, World!

Example 2: Display a message with a newline:

PS C:> Write-Host “This is a message with a newline.`nThis is the second line.”
This is a message with a newline.
This is the second line.

Example 3: Display a message in a specific color:

PS C:> Write-Host “This is a red message.” -ForegroundColor Red
This is a red message.

Example 4: Display a message in a specific font and background color:

PS C:> Write-Host “This is a message in Arial font and yellow background.” -FontName Arial -BackgroundColor Yellow
This is a message in Arial font and yellow background.

In these examples, the Write-Host cmdlet is used to display different types of messages on the console.

The -ForegroundColor and -BackgroundColor parameters can be used to specify the color of the text and background, respectively, and the -FontName parameter can be used to specify the font of the text.

Example 5: Display a message with a warning icon:

PS C:> Write-Host “This is a warning message.” -ForegroundColor Yellow -BackgroundColor Red -NoNewline -WarningAction Continue

Example 6: Display a message and wait for user input:

PS C:> Write-Host “Press any key to continue…”
Press any key to continue…
$x = $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)

Example 7: Display a message and wait for a specific key to be pressed:

PS C:> Write-Host “Press the ‘Y’ key to continue, or any other key to exit…”
Press the ‘Y’ key to continue, or any other key to exit…
$x = $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)
if ($x.Character -eq “Y”) {
Write-Host “Continuing…”
} else {
Write-Host “Exiting…”
exit
}

In these examples, the Write-Host cmdlet is used to display different types of messages and to prompt the user for input. The -NoNewline parameter is used to prevent a newline from being added after the message, and the -WarningAction parameter is used to specify the action to be taken when a warning message is displayed. The $host.UI.RawUI.ReadKey method is used to read user input from the console.

Example 8: Display a message with a progress bar:

$count = 0
$maximum = 100
$progress = 0
$block = “#”
while ($count -lt $maximum) {
$count++
$percent = [math]::Round(($count/$maximum)*100)
$newProgress = [math]::Round($percent/2)
if ($newProgress -gt $progress) {
$progress = $newProgress
Write-Host “Progress: $percent% $($block * $progress)” -NoNewline
}
Start-Sleep -Milliseconds 50
}

Example 9: Display a message with a spinning cursor:

$spin = “|/-\”
$count = 0
while ($true) {
$count++
Write-Host “$($spin[$count % 4]) Loading… ” -NoNewline
Start-Sleep -Milliseconds 200
}

Example 10: Display a message with a custom font and size:

$font = New-Object System.Drawing.Font(“Comic Sans MS”,16,[System.Drawing.FontStyle]::Bold)
$color = [System.Drawing.Color]::Blue
Write-Host “This is a message with a custom font and size.” -ForegroundColor $color -Font $font

In these examples, the Write-Host cmdlet is used to display different types of messages with custom formatting. The -NoNewline parameter is used to prevent a newline from being added after the message, and the Start-Sleep cmdlet is used to pause the script for a specified number of milliseconds. The New-Object cmdlet is used to create a custom font object, and the [System.Drawing.Color] type is used to specify a color.

Example 11: Display a message with a custom alignment:

$string = “This is a message with custom alignment.”
$length = $string.Length
$padding = [math]::Ceiling($length / 2)
Write-Host $string -PaddingLeft $padding

Example 12: Display a message with a custom tab size:

$tabSize = 4
$string = “`tThis is a message with a custom tab size.”
Write-Host $string -Tab $tabSize

Example 13: Display a message with custom formatting using a script block:

$string = “This is a message with custom formatting.”
$format = {
param($string)
$string.ToUpper()
}
Write-Host $string -ForegroundColor Yellow -BackgroundColor Red -InvokeReturnAsIs $format

In these examples, the Write-Host cmdlet is used to display messages with custom formatting. The -PaddingLeft parameter is used to specify the left padding of the message, the -Tab parameter is used to specify the tab size, and the -InvokeReturnAsIs parameter is used to specify a script block that is used to format the message.

The [math]::Ceiling method is used to round up to the nearest integer, and the ToUpper method is used to convert the string to uppercase.

PowerShell write-host as table

To display output as a table in PowerShell, you can use the Format-Table cmdlet. The Format-Table cmdlet takes objects as input and formats them as a table, with each property of the object displayed as a column.

Here is an example of using the Format-Table cmdlet to display a table of process information:

PS C:> Get-Process | Format-Table Name, Id, Path
Name Id Path
—- — —-
svchost 1844 C:\Windows\System32\svchost.exe
svchost 4 C:\Windows\System32\svchost.exe
conhost 844 C:\Windows\System32\conhost.exe

In this example, the Get-Process cmdlet is used to retrieve a list of processes running on the system, and the Format-Table cmdlet is used to format the output as a table. The Name, Id, and Path properties of the process objects are displayed as columns in the table.

You can also use the Write-Host cmdlet to display the formatted table output. For example:

PS C:> $processes = Get-Process | Format-Table Name, Id, Path
PS C:> Write-Host $processes

This will display the table output on the console.

You can customize the appearance of the table by using the various parameters of the Format-Table cmdlet. For example, you can use the -AutoSize parameter to automatically resize the columns to fit the content, or the -Wrap parameter to wrap the content of a column.

Conclusion

Write-Host is fully permitted for usage and recommended when you’re about to show informative messages to the user, thanks to the improvements in PowerShell 5.x and on.

Because a PowerShell user has the same degree of control over an informational message as an outgoing or verbose message, using With PowerShell Write Host or Write-Information is advised and recommended.

As always, I like to get feedback from you. In the comment section, drop some of how you used the PowerShell Write Host command.