2

我有以下函数,它采用文件名并在本地或使用环境路径解析它。我正在寻找与命令行相同的功能:

function Resolve-AnyPath ($file)
{
    if ($result = Resolve-Path $file -ErrorAction SilentlyContinue)
    {
        return $result;
    }

    return ($env:PATH -split ';') |
        foreach {
            $testPath = Join-Path $_ $file
            Resolve-Path $testPath -ErrorAction SilentlyContinue
        } |
        select -first 1
}

我的问题:

  1. 有没有内置函数可以做到这一点?
  2. 还是更好的社区脚本?
  3. 我上面的功能有什么遗漏吗?
4

2 回答 2

4

对于 exes(和 $env:PATHEXT 中的其他扩展),您可以使用Get-Command. 它将搜索路径,例如:

C:\PS> Get-Command ProcExp.exe | Foreach {$_.Path}
C:\Bin\procexp.exe
于 2012-10-09T21:46:23.297 回答
2

想不出有任何内置函数可以做到这一点。我会Test-Path用来摆脱那些SilentlyContinue

function Resolve-Anypath
{
    param ($file)

    (".;" + $env:PATH).Split(";") | ForEach-Object {
        $testPath = Join-Path $_  $file
        if (Test-Path $testPath) {
            Write-Output ($testPath)
            break
        }
    }
}
于 2012-10-09T19:52:17.013 回答