How To Use Try Catch With Set Location and ErrorActionPreference in Powershell
The aim of this page📝 is provide steps for a short cdf
function that navigates to the selected folder in fzf
even if you select a file. Selecting a file would end up in non terminating error as you need a container for the Set-Location
command. But I want to change folders quickly anyway...
1 min readJun 26, 2023
try-catch
block handles errors in PowerShell script.cd
command is an alias forSet-Location
cmdlet.- Non-terminating errors generated by
Set-Location
are by default not caught bytry-catch
. $ErrorActionPreference
variable controls how PowerShell responds to non-terminating errors.- Set
$ErrorActionPreference
to'Stop'
to make non-terminating errors behave like terminating errors.
function cdf {
try {
$ErrorActionPreference = 'Stop'
Set-Location (fzf)
}
catch {
Set-Location (Split-Path (fzf))
}
finally {
$ErrorActionPreference = 'Continue'
}
}
In this example, $ErrorActionPreference
is set to 'Stop'
before calling Set-Location
. If Set-Location
generates a non-terminating error, the error will be caught by the catch
block and the second Set-Location
statement will be executed. In the finally
block, $ErrorActionPreference
is reset to 'Continue'
.