Understanding Write-Verbose in PowerShell
Welcome back to Wahmans Powershell blog! Today we are diving into one of the lesser-appreciated yet incredibly useful cmdlets in PowerShell: Write-Verbose.
According to Microsoft Docs, the Write-Verbose cmdlet “writes text to the verbose message stream.” But what does that mean in practice? Let’s unpack it.
What is Write-Verbose?
Write-Verbose is useful for outputting additional information about what your script is doing. These messages are only shown when the -Verbose parameter is used during script or function execution. This allows you to keep normal output clean while still giving detailed information when needed for debugging or understanding script flow.
Beginner to Advanced Examples
Example 1: Simple Verbose Message
Write-Verbose "Starting script execution"
When you run this line normally, you won’t see anything. But if you run it like this:
Write-Verbose "Starting script execution" -Verbose
You will see: VERBOSE: Starting script execution
Example 2: Verbose in a Function
function Get-Greeting {
[CmdletBinding()]
param (
[string]$Name
)
Write-Verbose "Generating greeting for $Name"
"Hello, $Name"
}
Get-Greeting -Name "Sara" -Verbose
This outputs the greeting and includes the verbose message if -Verbose is specified.
Example 3: Conditional Debugging in Scripts
$logVerbose = $true
if ($logVerbose) {
Write-Verbose "Verbose logging is enabled"
}
This setup allows toggling verbose output selectively – useful in larger scripts. Don’t forget to run the script with -Verbose to see the output.
Example 4: Detailed Logging in Loops
function Test-Loop {
[CmdletBinding()]
param ()
for ($i = 1; $i -le 5; $i++) {
Write-Verbose "Processing item $i"
"Item: $i"
}
}
Test-Loop -Verbose
This function outputs verbose status for each iteration of the loop—great for tracking script flow in complex logic.
Final Thoughts
Write-Verbose is a great tool for adding transparency and traceability to your PowerShell scripts. It keeps your visible output clean while giving you the option to see behind the scenes when needed.
Happy scripting, and I will see you in the next post!
Leave a Reply