我一直在试图创建一个用于在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的输出已经失去了颜色。有什么建议么?
这确实是一件我会考虑。谢谢您的帮助! –