测试PowerShell中的可执行文件是否在路径中

时间:2012-06-28 10:10:49

标签: powershell

在我的脚本中,我即将运行一个命令

pandoc -Ss readme.txt -o readme.html

但我不确定是否安装了pandoc。所以我想做(伪代码)

if (pandoc in the path)
{
    pandoc -Ss readme.txt -o readme.html
}

我怎样才能真正做到这一点?

2 个答案:

答案 0 :(得分:94)

您可以通过Get-Command (gcm)

进行测试
if (Get-Command "pandoc.exe" -ErrorAction SilentlyContinue) 
{ 
   pandoc -Ss readme.txt -o readme.html
}

如果您想测试路径中不存在命令,例如显示错误消息或下载可执行文件(想想NuGet):

if ((Get-Command "pandoc.exe" -ErrorAction SilentlyContinue) -eq $null) 
{ 
   Write-Host "Unable to find pandoc.exe in your PATH"
}

尝试

(Get-Help gcm).description

在PowerShell会话中获取有关Get-Command的信息。

答案 1 :(得分:2)

这是David Brabant回答的一个功能,检查最低版本号。

    manager.delegate.sessionDidReceiveChallenge = { session, challenge in
        var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
        var credential: URLCredential?

        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust {
            disposition = URLSession.AuthChallengeDisposition.useCredential
            credential = URLCredential(trust: trust)
        } else {
            if challenge.previousFailureCount > 0 {
                disposition = .cancelAuthenticationChallenge
            } else {
                credential = self.manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

                if credential != nil {
                    disposition = .useCredential
                }
            }
        }

        return (disposition, credential)
    }

这允许您执行以下操作:

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"
        }
    }
}

如果满足要求则不执行任何操作或抛出错误。