2012-06-28 43 views
37

Trong kịch bản của tôi Tôi về để chạy một lệnhPowershell kiểm tra nếu thực thi trong đường dẫn

pandoc -Ss readme.txt -o readme.html 

Nhưng tôi không chắc chắn nếu pandoc được cài đặt. Vì vậy, tôi muốn làm (pseudocode)

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

Làm cách nào để thực hiện điều này?

Trả lời

70

Bạn có thể kiểm tra thông qua Get-Command (gcm)

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

Nếu bạn muốn thử nghiệm sự không tồn tại của một lệnh trong đường dẫn của bạn, ví dụ để hiển thị một thông báo lỗi hoặc tải tập tin thực thi (nghĩ NuGet):

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

Hãy thử

(Get-Help gcm).description 

trong một phiên PowerShell để có được inf ormation về Get-Command.

+1

Cảm ơn David. Làm thế nào tôi có thể làm điều này một cách duyên dáng, làm im lặng lỗi lớn màu đỏ? –

+1

Vì không ai nói, "-ErrorAction SilentlyContinue" thêm vào sẽ giết chết lỗi lớn màu đỏ. –

+1

Tôi đã sử dụng 'where.exe' và kiểm tra mã thoát, nhưng đó không phải là lệnh PS. – orad

1

Chỉ trong trường hợp một số thấy hữu ích. Đây là một chức năng theo tinh thần của câu trả lời của David Brabant với một kiểm tra cho số phiên bản tối thiểu.

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

này cho phép bạn làm như sau:

Ensure-ExecutableExists -Executable pscp -MinimumVersion "0.62.0.0" 

Nó làm gì nếu yêu cầu được đáp ứng hay ném một lỗi nó không phải là.

Các vấn đề liên quan