[PowerShell] Built-in support for -Debug and -Verbose for your scripts

Here is very good article about adding support for so-called Common Parameters such as -Verbose or -Debug

Short overview of the article above

To enable support for Common Parameters you need to add the following snippet on top of your script

[CmdletBinding()]
Param ()

So now you can invoke

.\MyScript.ps1 -Debug -Verbose

If you don’t like the fact that your script breaks on every Write-Debug you can use the following snippet

if ($PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent) 
{
     $DebugPreference = "Continue"
}

Another approach to enable Write-Debug and Write-Verbose everywhere would be to add the following snippet into your PowerShell profile script

$global:DebugPreference = "Continue"
$global:VerbosePreference = "Continue"

It is especially useful if you have a complex chain of calls and you don’t want to modify all of them.

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized 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