This post is mostly for WFA designers who write/debug powershell code.
Powershell and WFA can work wonders for your automation solution. However if you have to debug some error in code, this can get tricky for you. I'm writing this from my own experience all the difficulties I face when when debugging powershell code. Powerhsell is available as code language at Data Source Type script and Commands.
If a failure occurs , WFA throws only exception, but it can be difficult to know which line of the code caused it. Powershell throws many generic exceptions like 'you cannot call a method on a null-valued expression'. This is all what is shown by WFA and very difficult to figure where has this error occurs.
The same difficulty is in Data Source script, actually worse. I only see one-line of Exception and I'm totally left to find which line of code has thrown it.
WFA powerhsell code also uses WFA cmdlets which don't work outside of WFA. So I can't even copy the faulty code in Powershell ISE and test it. I would need to make many changes to get it working outside.
I'm sharing something I've bee using for many years now. I hope this can help others.
To know the location of the exception, add a trap . Trap is like a universal catch block for the powershell code.
Example: WFA Command
Original Command Code is a extremely simple powershell code.
[parameter(Mandatory=$true, HelpMessage="Message to print")]
#Line that throws an error $throw.Error()
Get-WfaLogger -Info -Message $Message
Testing this command code will give error log like this
18:07:47.309 INFO [Print a Message] ### Command 'Print a Message' in 'POWER_SHELL' ###
18:07:48.854 ERROR [Print a Message] You cannot call a method on a null-valued expression.
18:07:48.932 ERROR [Print a Message] Failed executing command. Exception: You cannot call a method on a null-valued expression.
No where I can know which line is throwing this exception. If my code was complex, I would really struggle.
To aid you in debugging, Just add a trap like below. Its a universal trap code and will work for all commands.
Now when you test this command code, the output is:
18:12:38.566 INFO [Print a Message] ### Command 'Print a Message' in 'POWER_SHELL' ###
18:12:40.222 ERROR [Print a Message] Error Occurred at Code "$throw.Error()
" Line: 7 Char: 1
18:12:40.247 ERROR [Print a Message] You cannot call a method on a null-valued expression.
18:12:40.345 ERROR [Print a Message] Failed executing command. Exception: You cannot call a method on a null-valued expression.
$_ variable has many other attributes which can be used to help you in debugging.
Now you know which line in your code is throwing this error. Take it from here, your first aid to fixing your code is complete.
Example: Data Source Script
WFA doesn't have good built-in logging mechanism for Data Source script. So use this Logger
Once your logger is ready, Add the below trap in your Powershell code.