Test if executable is in path in PowerShell

Powershell

Powershell Problem Overview


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?

Powershell Solutions


Solution 1 - Powershell

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 - Powershell

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionColonel PanicView Question on Stackoverflow
Solution 1 - PowershellDavid BrabantView Answer on Stackoverflow
Solution 2 - PowershellBrunoView Answer on Stackoverflow