Write-Error and -TargetObject

Sometimes I feel like I know a lot about PowerShell.  I’ve taught dozens of classes on PowerShell, written two books, and used it for 8 years now.

And then I stumble upon this post from Jeffery Snover in 2006.xI’m not even sure now why I was looking at it at the end of 2015.   The post is about -ErrorAction and -ErrorVariable.  I’m very comfortable with those two common parameters.  Nothing to see there.  But in scanning down the page, my eye stopped in the middle of a screenshot.

TargetObject

There in the “forced” output of the $Error variable I see something I hadn’t ever seen before. TargetObject.

One of the keys of non-terminating errors is that hypothetically you can address the errors that happen while allowing the rest of the “payload” to continue. For example, you stopped 50 processes but one failed. You wouldn’t want to give up when that process failed. You’d rather finish the list and then do something about that one process.  It’s pretty clear to see in the screenshot that the TargetObject in this case was “13”.  You can do something with that.

Non-terminating errors are a basic part of PowerShell, but I don’t remember hearing or reading about this ever before.

Sure enough, though, there’s a -TargetObject parameter in Write-Error:

TargetObjectParameter

And the example in the post showed that the parameter is used when Stop-Process has an error. Why hadn’t I ever seen it before?

Ah, I know. My standard example when explaining non-terminating errors looks like this:

gwmi Win32_OperatingSystem -computername NOSUCHCOMPUTER,localhost

The $Error object written by Get-WMIObject looks like this:
WMIError

Unfortunately the TargetObject property is empty. Since Get-WMIObject implicitly loops through the ComputerNames, it would be super useful to know the name of a computer where the operation failed.

It will be fun to look through cmdlets to see which ones correctly use this parameter.

My new “best practice”:

Always populate -TargetObject when calling Write-Error

As always, let me know what you think in the comments.

–Mike

P.S.  I’ve filed a bug for Get-WMIObject on uservoice here.  Please take a minute to upvote it.