How To Test For Application In $Env:PATH?

Line Break

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"
}
Bookmark and Share

Author:Frank-Peter
Date: Sunday, 18. October 2009 11:02
Trackback: Trackback-URL Category: Scripting, Windows PowerShell

Feed for the post RSS 2.0 Comment this post

Submit comment

CAPTCHA Image CAPTCHA Audio
Refresh Image