![](/img/trans.png)
[英]Why is PowerShell “not recognized” when installing Chocolatey?
[英]Try/catch in PowerShell when installing Chocolatey packages
我一直在尝试创建用于在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:\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
这将使我有机会询问用户是否希望使用--force参数重新运行脚本。 唯一的问题是choco的输出失去了颜色。 有什么建议么?
需要Windows Management Framework 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
(我将在明天将此标记为答案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.