How To Test For Application In $Env:PATH?
Author: Frank-Peter (77 Articles)
Let’s assume your PowerShell script depends on a utility like robocopy.exe or sc.exe that is in a path listed in the Path environment variable ($Env:Path). Naturally, you want to test if that utility is present. While the Test-Path Cmdlet doesn’t take the Path environment variable into account the Get-Command Cmdlet is designed to consider that variable.
The function below, Test-EnvPath, uses Get-Command and returns True if the tested utility exists:
function Test-EnvPath
{
param (
[string]$Name = $(Read-Host "Supply a value for the Name parameter")
)
[array]$test = Get-Command -Name $Name -CommandType Application -ErrorAction SilentlyContinue
if ($test.Count)
{
return $true
}
else
{
return $false
}
}
The usage of Test-EnvPath is pretty simple:
if (-not (Test-EnvPath robocopy.exe))
{
Write-Host "Required utility not found - robocopy.exe"
}