Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell resolving file with environmental path

I have the following function that takes a file name and resolves it either locally, or with the environmental path. I'm looking for the same functionality as you get on the command line:

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
}

My questions:

  1. Is there a built-in function that does this?
  2. Or a community script that's better?
  3. Did I miss anything with my function above?
like image 397
alejandro5042 Avatar asked Apr 01 '26 07:04

alejandro5042


2 Answers

For exes (and other extensions in $env:PATHEXT), you can use Get-Command. It will search the path e.g.:

C:\PS> Get-Command ProcExp.exe | Foreach {$_.Path}
C:\Bin\procexp.exe
like image 163
Keith Hill Avatar answered Apr 02 '26 22:04

Keith Hill


Cannot think of any built-in function that does this. I'd use Test-Path to get rid of those SilentlyContinue:

function Resolve-Anypath
{
    param ($file)

    (".;" + $env:PATH).Split(";") | ForEach-Object {
        $testPath = Join-Path $_  $file
        if (Test-Path $testPath) {
            Write-Output ($testPath)
            break
        }
    }
}
like image 24
Torbjörn Bergstedt Avatar answered Apr 02 '26 22:04

Torbjörn Bergstedt