Write-Verbose cmdlet

Overview

I was doing some PowerShell scripting recently which used the Write-Verbose cmdlet. At first I couldn’t get this to work as expected and had no idea what was wrong. After some digging around, I found that:

Quote

By default, the verbose message stream is not displayed, but you can display it by changing the value of the $VerbosePreference variable or using the Verbose common parameter in any command.

Unquote.

Investigation

I used the following script blocks in a script to demonstrate the relationship between the Write-Verbose cmdlet and the variable VerbosePreference. I used script blocks merely to contain the code for each individual test.

Scriptblock 1

Verbose messages displayed.

& {
    # This section displays verbose messages as expected.
    Write-Host "Part one";
    $VerbosePreference = "Continue";
    Write-Host "Scriptblock one";
    Write-Verbose -Message	"verbose test	message	one	we expect	to see";
}

Scriptblock 2

Verbose messages suppressed.

$ExecutionContext.InvokeCommand.InvokeScript( {
  # This section suppresses verbose messages.
  Write-Host "`nPart two";
  $VerbosePreference = "SilentlyContinue";
  Write-Host "Scriptblock two";
  Write-Verbose -Message "verbose test message two we don't see";
}
)

The command ExecutionContext.InvokeCommand.InvokeScript is just another way of executing a scriptblock. It doesn’t have to be done this way, you can use the Call Operator “&” if you wish. I left this in to remind me of an alternate way of executing scriptblocks if I need to.

Scriptblock 3

Verbose messages displayed regardless of the setting of variable VerbosePreference because we’re using the common parameter Verbose.

& {
   # All verbose test messages are displayed regardless of the
   # setting of variable VerbosePreference.
   Write-Host "`nPart three";
   $VerbosePreference = "Continue";
   Write-Verbose -Message "Part three - verbose test message one" -Verbose;

   $VerbosePreference = "SilentlyContinue";
   Write-Verbose -Message "Part three - verbose test message two" -Verbose;
}

Sumary

  • $VerbosePreference = “Continue” – verbse message displayed.
  • $VerbosePreference = “SilentlyContinue” – verbose message suppressed.

See also

PowerShell Script Blocks

Command Discovery and Scriptblocks

about_CommonParameters this article contains a description of the common parameter Verbose among others.

Reference

Microsoft TechNet article Write-Verbose

Advertisements
This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s