2016-07-25 83 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

这确实是一件我会考虑。谢谢您的帮助! –