Adam Bertram
Adam Bertram

Reputation: 4188

How to tracing script flow

I'm fairly new to Powershell and have written some pretty large scripts ie a script that calls others scripts which have functions nested in other functions. When I launch this script I sometimes get errors that I don't know where they came from. Is there an easy way to see where this script terminated so I can troubleshoot the error?

Upvotes: 7

Views: 6723

Answers (3)

Andy Arismendi
Andy Arismendi

Reputation: 52619

For debugging to see where your error's are coming from I suggest debugging with the ISE or with PowerGUI.

You can also get a transcript of you script using the Start-Transcript cmdlet which will write all console activity to file. So you can put statements such as Write-Host "Doing XYZ" and those will show up in the transcript log.

If you catch exceptions with a try catch or use a trap you can write the line number and column of the exception like this:

$ErrorActionPreference = 'Stop'

trap {
  Write-Host "Error on line $($_.InvocationInfo.ScriptLineNumber)"
  exit 1
}

try {
    Get-Item DoesntExist
} catch {
    Write-Host ("Error occurred on line: " + $_.InvocationInfo.ScriptLineNumber)
}

$_.InvocationInfo has other details about were the error is coming from.

By setting $ErrorActionPreference = "Stop" you ensure that any error triggers the trap{} block, which in this case writes out the line the script got to and exits.

Upvotes: 4

MrKWatkins
MrKWatkins

Reputation: 2658

You can use Set-PsDebug to get PowerShell to output almost every line it runs:

Set-PSDebug -Trace 1;

Only downside is you'll probably end up with a lot of output to wade through...

Upvotes: 14

Arcass
Arcass

Reputation: 932

Normally the error includes the calling script.

Failing that you could try running the script ofr the Window PowerShell ISE in debug mode. This allows you to use break points and step through code.

Artile on using the ISE for debugging:

ISE debugging

regards Arcass

Upvotes: 0

Related Questions