Alex Rivera | Logout

Support Verbose in PowerShell script

Asked 2011-12-12T04:07:18.877
25

I'm creating a .ps1 script which invokes Write-Verbose. I would like to be able to enable/disable these.

I was hoping that I could pass the -Verbose flag when invoking the script and everything would just work. Unfortunately this doesn't seem to be the case.

The verbose messages are not written out to the host. I looked around a bit and found Supporting -Whatif, -Confirm, -Verbose – In SCRIPTS!

But this is from 2007 and the PS team member stated that they were looking for built in support in PS v2.

Anybody have any updates on this or do we have to use the same technique described in that blog post?

Here is an example of the current behavior.

I created a simple script,ex01.ps1, with the following.

Write-Host "line 1"
Write-Verbose "line 2"
Write-Host "line 3"

I first executed the script with .\ex01.ps1, and only 1 & 2 were printed as expected. Then I executed it with .\ex01.ps1 -verbose, and got the same result. I was expecting all 3 lines to be printed the second time.

Powershell example result

Edit
Report

2 Answers

27

In order to have the Verbose switch you need to specify the CmdletBinding attribute in your script. To add support for the Confirm and WhatIf switches, add the SupportsShouldProcess attribute and call the ShouldProcess method in the script:

## content of .\ex01.ps1 ##
[CmdletBinding(SupportsShouldProcess=$true)]
Param()
Write-Host "line 1"
Write-Verbose "line 2"
Write-Host "line 3"

if($PSCmdlet.ShouldProcess($env:COMPUTERNAME,'Remove X'))
{
    "do something"
}


###########################


PS > .\ex01.ps1
line 1
line 3

PS > .\ex01.ps1 -Verbose
line 1
VERBOSE: line 2
line 3

PS > .\ex01.ps1 -WhatIf
line 1
line 3
What if: Performing operation "Remove X" on Target "PC1".
answered 2011-12-12T07:44:30.980
5

You shoul have a look to Advanced Functions : With Advanced functions you can take advantage of the common -verbose parameter. Simply output your verbose output this way:

Write-Verbose "Text of debug"

And when the shell's $VerbosePreference variable isn't set to "SilentlyContinue" ("Continue" will enable the output), you'll see your verbose output.

This Windows IP Pro Article Part1 and spcialy Part2 discribes what else you can do with advanced functions. You can also find a step by step guide in A guide to PowerShell’s Advanced Functions

answered 2011-12-12T04:32:46.753

Your Answer