我一直在試圖創建一個用於在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的輸出已經失去了顏色。有什麼建議麼?
這確實是一件我會考慮。謝謝您的幫助! –