How to track thread script

I am new to Powershell and have written some pretty large scripts, i.e. script that calls other scripts whose functions are nested in other functions. When I run 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 is completed so that I can fix the error?

+7
source share
3 answers

You can use Set-PsDebug to force PowerShell to print almost every line:

 Set-PSDebug -Trace 1; 

The only drawback is that you will probably end up with a lot of output to get through ...

+12
source

For debugging, to find out where your error is coming from, I suggest debugging using ISE or PowerGUI.

You can also get the transcript for you script using the Start-Transcript cmdlet, which will write all the console activity to a file. So you can put expressions like Write-Host "Doing XYZ" and they will appear in the protocol log.

If you catch exceptions with a try catch or use a trap, you can write the row number and the exception column as follows:

 $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 contains other information about whether an error occurred.

By setting $ErrorActionPreference = "Stop" , you will make sure that any error starts the trap{} block, which in this case writes the line where the script is located.

+4
source

Typically, an error involves calling a script.

Otherwise, you can try running the script of the Window PowerShell ISE in debug mode. This allows you to use breakpoints and execute code.

Artile when using ISE for debugging:

ISE Debugging

Regards Arcass

0
source

All Articles