【发布时间】:2022-11-10 22:13:31
【问题描述】:
我有一个“主”powershell 脚本,它执行多个在 VM 上安装应用程序的脚本。我正在尝试在主脚本上实现错误控制,这意味着:
如果安装应用程序的脚本之一失败,则不会执行其余脚本。
这是我的主要脚本:
try{
powershell.exe -ExecutionPolicy Unrestricted -File 'C:\\TEST\\Scripts\\App1.ps1'
powershell.exe -ExecutionPolicy Unrestricted -File 'C:\\TEST\\Scripts\\App2.ps1'
powershell.exe -ExecutionPolicy Unrestricted -File 'C:\\TEST\\Scripts\\App3.ps1'
}catch
{
Write-Host "Error"
}
这是安装应用程序的脚本之一(App2.ps1)的示例(所有脚本都遵循与此相同的逻辑)
#Set logging
$logFile = "C:\TEST\Logs\" + (get-date -format 'yyyyMMdd') + '_softwareinstall.log'
function Write-Log {
Param($message)
Write-Output "$(get-date -format 'yyyyMMdd HH:mm:ss') $message" | Out-File -Encoding utf8 $logFile -Append
}
#Install APP2
$file = Test-Path "C:\TEST\Apps\APP2\APP2 x64 7.2.1.msi"
if($file)
{
try{
Write-Log "Installing App2"
Start-Process msiexec.exe -Wait -ArgumentList '/i "C:\TEST\Apps\APP2\App2 x64 7.2.1.msi" ALLUSERS=1 AddLocal=MiniDriver,PKCS,UserConsole,Troubleshooting,Help /qn /norestart'
if(Test-Path -Path "C:\Program Files\HID Global\APP2\ac.app2.exe")
{
Write-Log "App2 installed"
}
else
{
Write-Log "There was a problem while installing App2"
throw "There was a problem while installing App2"
}
}catch
{
Write-Log "[ERROR] There was a problem while starting the installation for App2"
throw "[ERROR] There was a problem while starting the installation for App2"
}
}
else
{
Write-Log "Installation file for App2 not found"
throw "Installation file for App2 not found"
}
(出于保密目的,我模糊了应用程序的名称)
安装APP2的脚本出现异常时,为什么主脚本继续执行? 不应该停止并显示写在主脚本中 catch 部分的消息吗?
先感谢您
【问题讨论】:
-
尝试将
$ErrorActionPreference = 'Stop'添加到脚本的开头 -
就是这样!非常感谢。我不知道这是这么简单的事情
-
很好的交易。乐意效劳。
-
顺便说一句:
\在 PowerShell 中没有特殊含义,因此它永远不需要转义为\\;例如,C:\TEST\Scripts\App1.ps1工作得很好。
标签: powershell