Has anyone implemented the equivalent behavior of bash's 'cdpath' in Powershell?
The Set-Location cmdlet sets the working location to a specified location. That location could be a directory, a subdirectory, a registry location, or any provider path. PowerShell 6.2 added support for - and + as a values for the Path parameter.
You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).
Did not know about CDPATH before. Good to know. I whipped up the below for Powershell:
function cd2 {
param($path)
if(-not $path){return;}
if((test-path $path) -or (-not $env:CDPATH)){
Set-Location $path
return
}
$cdpath = $env:CDPATH.split(";") | % { $ExecutionContext.InvokeCommand.ExpandString($_) }
$npath = ""
foreach($p in $cdpath){
$tpath = join-path $p $path
if(test-path $tpath){$npath = $tpath; break;}
}
if($npath){
#write-host -fore yellow "Using CDPATH"
Set-Location $npath
return
}
set-location $path
}
It will not be perfect, but works in the expected way. You can extend it I guess. Add it to your profile. If needed, also add an alias like so:
set-alias -Name cd -value cd2 -Option AllScope
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