Test if executable is in path in PowerShell

前端 未结 2 1538
一生所求
一生所求 2020-12-28 11:25

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 w

2条回答
  •  有刺的猬
    2020-12-28 12:00

    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.

提交回复
热议问题