2016-07-25 50 views
0

我一直在試圖創建一個用於在PowerShell中安裝Chocolatey包的腳本。這工作正常,但我想分析巧克力的輸出。我在想的是類似於在安裝Chocolatey包時嘗試/捕獲PowerShell

$package = "something I want" 
try   
{ 
    $installCommand = "choco install $package" 
    iex $installCommand -ErrorAction Stop -WarningAction Stop 
} 
catch 
{ 
    #Print error messages, i.e. $_.Exception.Message 
} 

我是PowerShell的新手,我試圖弄清楚如何使用try/catch。我試過

try { 
    $command = "choco install asdasdasdasdasdad" 
    iex $command -ErrorAction Stop -WarningAction Stop 
} 
catch { 
    $message = $_.Exception.Message 
    Write-Host $message 
} 

但是這給了我

Installing the following packages: asdasdasdasdasdad 
By installing you accept licenses for the packages. 
asdasdasdasdasdad not installed. The package was not found with the source(s) listed. 
If you specified a particular version and are receiving this message, it is possible that the package name exists but the version does not. 
Version: "" Source(s): "https://chocolatey.org/api/v2/" 

Chocolatey installed 0/1 package(s). 1 package(s) failed. 
See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log). 
Failures: 
    - asdasdasdasdasdad 

任何提示嗎?提前,謝謝!


我發現了一個代碼示例,可以幫助我對我的方式:

function testInstall 
{ 
    Param (
     [string] $package 
    ) 

    Begin 
    { 
     Write-Host "Now in Begin.. Going on!" 
    } 
    Process 
    { 
     Write-Host "Starting Process" 
     Write-Host "" 

     $chocoCommand = "choco install $package" 
     iex $chocoCommand 

     Write-Host "" 
     Write-Host "Ending Process" 
    } 

    End 
    { 
     Write-Host "Now in End" 
    } 



} 

Function Test-Demo 
{ 
    Param ($Param1) 
    Begin { 
     write-host "Starting" 
    } 
    Process { 
     if($_ -eq " Use --force to reinstall, specify a version to install, or try upgrade.") 
     { 
     $forceDetected = $true; 
     } 
     write-host $_ 
    } 
    End { 

     if($forceDetected -eq $true) 
     { 
      Write-Warning "Force detected" 
      Write-Warning "Do you want to re-run the installer with --force?" 
      # Promt the user Y/N option and re-run testInstall -package $package --force 

     } 
     write-host "Ending" 
    } 
} 

testInstall -package ruby | Test-Demo Sample 

這將讓我有機會詢問用戶是否他/她想要重新運行與腳本 - 強制參數。唯一的問題是choco的輸出已經失去了顏色。有什麼建議麼?

回答

0

後一些測試,我做了這個。它在開發中,但它解析輸出,並且可以在最後打印安裝摘要(或任何我最終要做的事情)。

隨時發表評論。

https://github.com/bpjohannessen/ChocoPower

(我將在明天紀念這個作爲回答)

1

需要Windows管理框架5:

register-packagesource -Name chocolatey -Provider PSModule -Trusted -Location http://chocolatey.org/api/v2/ -Verbose 

我發現這個在這裏:https://serverfault.com/questions/633576/how-do-you-manually-set-powershells-oneget-repository-source-to-chocolatey

然後,您應該能夠像這樣運行的東西,並得到詳細的輸出:

Get-Package Nodejs | Install-Package -Verbose 
+0

這確實是一件我會考慮。謝謝您的幫助! –