Write Host - PowerShell
Overview
Write-Host is a PowerShell command that sends messages to the host console, providing a convenient way to display output and debug information. It’s commonly used for displaying user-friendly messages, debugging output, and troubleshooting scripts.
Syntax
Write-Host [-Object] <object> [-ForeColor <color>] [-BackgroundColor <color>] [-Width <pixels>] [-Expand]
Options/Flags
-Object: The object or message to be written to the host. Can be any valid PowerShell variable or expression.
-ForeColor: Sets the foreground color for the output text. Accepts any valid color name or hex value.
-BackgroundColor: Sets the background color for the output text. Accepts any valid color name or hex value.
-Width: Specifies the width, in pixels, of the output window. Useful for formatting output in specific widths.
-Expand: Expand all properties of the input object before writing it to the host.
Examples
Simple Message:
Write-Host "Hello, World!"
Coloring and Formatting:
Write-Host -Object 'Error: Command execution failed' -ForeColor Red -BackgroundColor Yellow
Expand Properties:
$process = Get-Process notepad
Write-Host -Object $process -Expand
Common Issues
- Missing Input: Ensure that the -Object parameter is specified and contains a valid object.
- Incorrect Color: Verify that the color names or hex values are correct and supported by your console.
- Truncated Output: If the output exceeds the console width, use the -Width option to adjust the output window size.
Integration
Concatenating Output: Write-Host can be used to combine multiple messages into a single line:
Write-Host -Object "Process started" -Object (Get-Date)
Logging: Write-Host can be redirected to a file for logging purposes:
Write-Host -Object "Operation completed" | Out-File -FilePath .\log.txt -Append
Related Commands
- Write-Debug: Writes debug messages to the debug console.
- Write-Warning: Writes warning messages to the host console.
- Write-Error: Writes error messages to the host console.
- Write-Output: Outputs objects to the pipeline for further processing.