Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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

(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?

like image 918
Chris Midgley Avatar asked Dec 06 '22 12:12

Chris Midgley


1 Answers

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:

try {
    $x = 1/0
}
catch {
    Write-Warning "An error occurred"
}
finally {
    Write-Output "This always runs"
}

More tailored to your situation:

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

like image 106
gvee Avatar answered Jan 16 '23 18:01

gvee