84

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?

1
  • Maybe which command of zsh in WSL is more useful, if you installed WSL. Commented Sep 23, 2021 at 11:15

2 Answers 2

154

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks David. How can I do this gracefully, silencing the big red error?
Since nobody said, the added "-ErrorAction SilentlyContinue" kills the big red error.
I used where.exe and checked the exit code, but that was not a PS command.
11

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.