Author Posts

February 18, 2014 at 12:10 pm

Ed offers this example of using $ErrorActionPreference:

Try {

$ErrorActionPreference = "Stop"

Copy-Item -Path $myfile -Destination $folder -Force }

CATCH [System.Exception]{

MD $folder | Out-Null

Copy-Item -Path $myfile -Destination $folder -Force }

FINALLY { $ErrorActionPreference = "Continue" }

You can also do this:

&{
Try {

$ErrorActionPreference = "Stop"

Copy-Item -Path $myfile -Destination $folder -Force }

CATCH [System.Exception]{

MD $folder | Out-Null

Copy-Item -Path $myfile -Destination $folder -Force }
}

Which isolates the $ErrorActionPreference in it's own scope. You don't have to worry about adding a FINALLY block to set it back. Since $ErrorActionPreference never changed in the parent scope, you also don't have to worry about whether setting it to 'Continue' will change what it was originally set to.

February 18, 2014 at 1:58 pm

All true. You have to be a bit careful with that technique, because any variables you create in that scope obviously won't persist in the rest of the script, but it's definitely an approach.

With cmdlets, of course, you can also use -ErrorAction on the cmdlet, which confines it to just that one command without creating a new scope.

And I suppose I could also argue that, with this specific example, Test-Path could have been used to avoid the error entirely. I personally tend to prefer test-and-recover vs. error-and-catch, when I'm in a situation to do so.

February 18, 2014 at 2:26 pm

I almost never wind up having to touch $ErrorActionPreference in a script, other than for demonstration purposes. I just use the ErrorAction parameter, and leave the preference variable alone.

February 19, 2014 at 11:57 am

The example is trivial enough that applying -ErrorAction to the relevant cmdlets instead of setting $ErrorActionPreference is pretty obvious. I'd consider setting it in a situation where I had a more complex script block where every operation depended on successful completion of all the ones before it, and any error should cause an immediate exit to the Catch block. Using the script block invocation to run it in it's own scope and protect the preference variable in the parent scope is just utilizing a scope for a purpose it was designed for. (IMHO).