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:
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
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
}
}
}
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