我有一个“主”powershell 脚本,它执行多个在虚拟机上安装应用程序的脚本。我正在尝试在主脚本上实现错误控制,意思是:
如果安装应用程序的脚本之一失败,则不会执行其余脚本。
这是我的主要脚本:
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"
}
Here is the output:
(出于保密目的,我模糊了应用程序的名称)
为什么安装APP2的脚本异常时主脚本继续执行?
不应该停止并显示主脚本中 catch 部分所写的消息吗?
先感谢您
按照建议我添加了$ErrorActionPreference = 'Stop'
到我的脚本的开头
$ErrorActionPreference = 'Stop'
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"
}
输出只是消息“Error”,在 catch 部分中指出。
谢谢至@道格·毛雷尔 https://stackoverflow.com/users/4085331/doug-maurer
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)