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?
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.
To perform a basic trace on a script: Open a PowerShell session. Run the following command: Set-PSDebug -Trace 1. Run your script.
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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With