7

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?

3 Answers 3

14

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...

1
  • This is exactly what I was looking for. However, I do see the big advantage in figuring out how to properly debug so I will look into that at a later time. Mar 2, 2012 at 21:35
4

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.

1
  • Added more about the trap{} handling of errors, since this enables general troubleshooting of any error without needing to put try{} catch{} around too many statements. Apr 8, 2016 at 22:09
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.