How do I revert a directory change in a PowerShell script when an uncaught exception is thrown?

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

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:

More tailored to your situation:

Results:

BEFORE: C:\temp

DURING TRY: C:\temp\csv

WARNING: An error occurred

AFTER: C:\temp

Source:

How do I revert a directory change in a PowerShell script when an uncaught exception is thrown? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply