如果脚本中的任何特定检查失败,powershell脚本可能会失败

时间:2017-03-27 05:21:57

标签: powershell

我有一个大脚本,我需要添加一个条件,当ADE检查失败时(即ADE安装失败),整个脚本状态应更改为Failed。谁能帮助我在这里添加一个条件?

 if (($ImageName -like "*devel*") -or ($ImageName -like "*hosted*"))
        {
            #$ADE1 = Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') | out-string ; $ADE = $ADE1.trim().split("")[1]
            Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') > C:\Temp\ade_check.txt 
            #Invoke-Command  -ScriptBlock { & 'C:\ade\bin\ade.exe' | Select-String -Pattern 'begintrans' > C:\Temp\ade_check.txt } -Credential $Credentials -ComputerName $env:COMPUTERNAME
            $ADE1 = Get-Content C:\Temp\ade_check.txt | Select-String "begintrans" | out-string ;  $ADE = $ADE1.trim().split(" ")[1]


            if ($ADE -eq "begintrans")
            {
            $ADE = "ADE Installation Success"


            Add-Content $report "<tr>"
                Add-Content $report "<td bgcolor= 'White'  height='30' align=center><B>17</B></td>"
            Add-Content $report "<td bgcolor= 'White'  height='30' align=left><B>ADE</B></td>"
            Add-Content $report "<td bgcolor= 'Aquamarine'  height='30' align=left><B>$ADE</B></td>"
            Add-Content $report "</tr>"

    echo "ADE = ADE Installation Success"

            }

            if ($ADE -eq $null){
            $ADE = "ADE Installation Failed"


            Add-Content $report "<tr>"
            Add-Content $report "<td bgcolor= 'White'  height='30' align=center><B>17</B></td>"
            Add-Content $report "<td bgcolor= 'White'  height='30' align=left><B>ADE</B></td>"
            Add-Content $report "<td bgcolor= 'red'  height='30' align=left><B>$ADE</B></td>"
            Add-Content $report "</tr>"

    echo "ADE = ADE Installation Failed"
            }

        }
        else
            {
            if (($ImageName -like "*simple*") -or ($ImageName -like "*BareOS*")){

            $ADE = "BareOS, ADE Not Installed"


            Add-Content $report "<tr>"
            Add-Content $report "<td bgcolor= 'White'  height='30' align=center><B>17</B></td>"
            Add-Content $report "<td bgcolor= 'White'  height='30' align=left><B>ADE</B></td>"
            Add-Content $report "<td bgcolor= 'Yellow'  height='30' align=left><B>$ADE</B></td>"
            Add-Content $report "</tr>"

    echo "ADE = BareOS, ADE Not Installed"
            }
            }

1 个答案:

答案 0 :(得分:0)

你应该永远不会以这种方式使脚本失败,而应该使用try / catch块来捕获它。但是,如果您仍希望在 “ADE安装失败” 的那一刻失败,那么您可以强制使用 退出 命令使脚本失败。

而不是:

if ($ADE -eq $null){
            $ADE = "ADE Installation Failed"


            Add-Content $report "<tr>"

执行此操作:

if ($ADE -eq $null){
            $ADE = "ADE Installation Failed"
exit 1

            Add-Content $report "<tr>"