Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tracing script flow

Tags:

powershell

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?

like image 262
Adam Bertram Avatar asked Mar 01 '12 14:03

Adam Bertram


People also ask

How to use script Tracer in servicenow?

To begin a trace, use the Application Navigator to open System Diagnostics > Script Tracer. The Script Tracer opens in a new window. Click the Start Tracer button. Return to the form being debugged and make whatever change is needed to trigger the scripts being debugged.

How do I trace a PowerShell script?

To perform a basic trace on a script: Open a PowerShell session. Run the following command: Set-PSDebug -Trace 1. Run your script.

How can I tell what PowerShell script is running?

status -eq "running"}" to view all running tasks on your machine. You can also pipe it to "Format-List * -Force" to view what location these scripts are running from.


2 Answers

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

like image 157
MrKWatkins Avatar answered Sep 23 '22 15:09

MrKWatkins


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.

like image 36
Andy Arismendi Avatar answered Sep 21 '22 15:09

Andy Arismendi