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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With