Showing posts with label Debugging. Show all posts
Showing posts with label Debugging. Show all posts

August 23, 2013

How to use write-verbose with an object

When you are debugging some times you want to use the write-verbose cmdlet to display an object or a collection.  It would have been really nice to be able to do :

write-verbose (Get-EventLog -LogName system -Newest 3 -EntryType Error)

unfortunately this will produce an error :

Write-Verbose : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Message'. Specified method is not supported.

The write-verbose cmdlet only takes a string as a paramter, objects are not allowed.
The trick is to use the out-string cmdlet like this :

write-verbose (Get-EventLog -LogName system -Newest 3 -EntryType Error | Out-String)

You can event make it look a little bit prettier :

write-verbose (Get-EventLog -LogName system -Newest 5 -EntryType Error| format-list -Property TimeGenerated,Entrytype,EventID,Source,Message | out-string)

February 13, 2013

How to add –whatif support to a function

 

Function Get-HelloWorld {
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="Low")]
    param()
    $message="Hello world"
    if ($PSCmdlet.ShouldProcess($message,"Write-host")) {
        write-host $message
    }
  }

Get-HelloWorld -whatif will produce :

What if: Performing operation "Write-host" on Target "Hello world".

As a bonus, you will also be able to use the -confirm and –verbose parameter

April 7, 2010

How to add some verbose to a script ?

In your script you can add the following command :

Write-verbose "Verbose message test"

Normally write-verbose output is not displayed, you can add the-verbose parameter when you call your script to active the display of verbose messages.

You can also add the following in your script to activate de display of verbose messages :

$VerbosePreference="Continue"

And the following to restore the normal behavior :

$VerbosePreference="SilentlyContinue"

Update : september 6, 2012

Yon can also add the follwing header to your script (event if you do not have parameters) :

[CmdletBinding()]
param()

This will allow your sctipt to support “common paramters “. You will be able to simply do the following instead of playing with the $VerbosePreference :

.\yourscript.ps1 -verbose

How to trace a script execution ?

To trace execution of every line, every function call and every variable affection in a script type the following command before running your script :

set-psdebug -trace 2 -step

To set thing back to normal :

set-psdebug -off