Test if executable is in path in PowerShell
In my script I'm about to run a command
pandoc -Ss readme.txt -o readme.html
But I'm not sure if pandoc
is installed. So I would like to do (pseudocode)
if (pandoc in the path)
{
pandoc -Ss readme.txt -o readme.html
}
How can I do this for real?
Solution 1:
You can test through Get-Command (gcm)
if (Get-Command "pandoc.exe" -ErrorAction SilentlyContinue)
{
pandoc -Ss readme.txt -o readme.html
}
If you'd like to test the non-existence of a command in your path, for example to show an error message or download the executable (think NuGet):
if ((Get-Command "pandoc.exe" -ErrorAction SilentlyContinue) -eq $null)
{
Write-Host "Unable to find pandoc.exe in your PATH"
}
Try
(Get-Help gcm).description
in a PowerShell session to get information about Get-Command.
Solution 2:
Here is a function in the spirit of David Brabant's answer with a check for minimum version numbers.
Function Ensure-ExecutableExists
{
Param
(
[Parameter(Mandatory = $True)]
[string]
$Executable,
[string]
$MinimumVersion = ""
)
$CurrentVersion = (Get-Command -Name $Executable -ErrorAction Stop).Version
If ($MinimumVersion)
{
$RequiredVersion = [version]$MinimumVersion
If ($CurrentVersion -lt $RequiredVersion)
{
Throw "$($Executable) version $($CurrentVersion) does not meet requirements"
}
}
}
This allows you to do the following:
Ensure-ExecutableExists -Executable pscp -MinimumVersion "0.62.0.0"
It does nothing if the requirement is met or throws an error it isn't.