有没有人在Powershell中实现了bash's 'cdpath'的等效行为?

最佳答案

以前不了解CDPATH。很高兴知道。我为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

}

它不会是完美的,但是会以预期的方式工作。我猜你可以扩展它。将其添加到您的个人资料。如果需要,还可以添加一个别名,如下所示:
set-alias -Name cd -value cd2 -Option AllScope

10-07 22:34