我一直在尝试创建一个脚本,用于在PowerShell中安装Chocolatey包。这很好,但我想解析Chocolatey的输出。我想的是类似的东西
$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:ProgramDatachocolateylogschocolatey.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
这将使我有机会询问用户是否希望重新运行带有--force参数的脚本。唯一的问题是choco的输出失去了颜色。有什么建议吗?
需要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
经过一些测试,我做了这个。它正在开发中,但它解析输出,我可以在最后打印安装摘要(或者我最终要做的任何事情)。
欢迎发表评论。
https://github.com/bpjohannessen/ChocoPower
(我明天会把它标记为答案)