Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDPATH functionality in Powershell?

Has anyone implemented the equivalent behavior of bash's 'cdpath' in Powershell?

like image 928
Tennis Smith Avatar asked Aug 29 '11 22:08

Tennis Smith


People also ask

What is set-location command 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.

How do I change the Path of a file in PowerShell?

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 (“”).


1 Answers

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
like image 103
manojlds Avatar answered Oct 23 '22 14:10

manojlds