Debugging Monad Scripts, Part 2: $error

Did your command or script fail and/or report an error? We hope to have a proper script debugger in a future version, but until then, MSH has some handy features to help you figure out what went wrong. In this series of blog entries, I will present some of those features. Thanks to Jim Truher [MSFT], Bruce Payette [MSFT], and Jeff Jones [MSFT] for their help in putting this together.

See the Windows "Monad" Shell Beta 2 Documentation Pack (https://www.microsoft.com/downloads/details.aspx?FamilyID=8a3c71d1-18e5-49d7-952a-c55d694ecee3&displaylang=en) for general information about Monad.

Part 1: https://blogs.msdn.com/monad/archive/2005/11/04/489138.aspx (Terminating vs. Non-Terminating Errors, ErrorRecord)

Jon Newman [MSFT]

$error

Errors occurring in MSH commands or scripts will be stored in $error. $error is always on, so you can use it even for errors which you can't reproduce (or would rather not repeat).

$error is an ArrayList containing the most recent errors: $error[0] is the most recent error, $error[1] the one before that, etc. $MaximumErrorCount (default 256) is the maximum number of errors which will be stored before the oldest is discarded.

So, when you see errors, you should have a look at $error[0]. Note that any new error will move $error[0] to $error[1], so you'll probably want to copy $error[0] to another shell variable before investigating it, e.g.

MSH C:\temp> start-service $servicename
start-service : Cannot bind argument to parameter 'ServiceName' because it is null.
At line:1 char:14
+ start-service <<<< $servicename
MSH C:\temp> $savethis = $error[0]
MSH C:\temp> $savethis.GetType().Name
ErrorRecord
MSH C:\temp> $savethis.InvocationInfo.MyCommand

CommandType Name Definition
----------- ---- ----------
Cmdlet start-service start-service [-ServiceName] String[] [-PassThru...

MSH C:\temp>

Note that Exception objects will in some cases also appear in $error. In particular, the "throw" script command may add both an ErrorRecord and a RuntimeException to $error.