Question:
In bash, if I wanted to change the current directory for a single command do_thing
, I’d spawn a new subshell in which to change the directory, running
1 2 |
(cd folderName; do_thing) |
The body of this question suggests the way to do it in PowerShell is to use Push-Location
to store the location, and Pop-Location
after the command has finished running. This works, but is not ideal: I have to remember write Pop-Location
at every return point of the script (e.g. before each exception, if it occurs while a location is pushed), and an uncaught exception will leave the current directory as is.
Is there a way to have the current directory reset to what it was at the start of the script, even if an uncaught exception is thrown?
Answer:
try...catch...finally
is the construct you’re looking for!
This will allow you to handle your errors and perform a final action; whether the main try block was successful or not.
Here’s a basic example:
1 2 3 4 5 6 7 8 9 10 |
try { $x = 1/0 } catch { Write-Warning "An error occurred" } finally { Write-Output "This always runs" } |
More tailored to your situation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Write-Output "BEFORE: $(Get-Location)" try { Push-Location -Path "C:\temp\csv" Write-Output "DURING TRY: $(Get-Location)" $x = 1/0 } catch { Write-Warning "An error occurred" } finally { Pop-Location } Write-Output "AFTER: $(Get-Location)" |
Results:
BEFORE: C:\temp
DURING TRY: C:\temp\csv
WARNING: An error occurred
AFTER: C:\temp