Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Error Handling Discussion

$
0
0

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.


Viewing all articles
Browse latest Browse all 13067

Trending Articles