【问题标题】:PowerShell Error handling : how to resolve if error occurs in first or middle of the script?PowerShell 错误处理:如果在脚本的开头或中间发生错误,如何解决?
【发布时间】:2020-07-05 08:02:58
【问题描述】:

我在我的 PowerShell 中调用了一个 bat 文件,并在 PowerShell 中给出了一个条件,如果它失败,它应该显示一条消息“失败”,如果它通过它将显示一条消息“通过”。我的 bat 文件包含单元测试用例,所以如果所有测试用例都通过了,我会在 powershell 中收到一条消息“通过”,并且如果所有测试用例都失败或最后一个测试用例在 bat 文件中失败,我会收到一条消息“失败”但我没有收到显示消息“失败”如果我的第一次测试那么如果第一次测试“失败”并且第二次测试“通过”而不是收到失败消息,我会收到通过消息。我使用了 $LASTEXITCODE 条件,它将给出测试(通过/失败)状态的最后状态。有什么办法可以解决这个问题。会很有用的。

demo.bat

@echo off
echo "running  test cases"
call npm run test folder1/file1/validate.test.js
call npm run test folder1/file2/validate.test.js

test.ps1

Write-Output "starting script......"
        .\demo.bat
    if ($LASTEXITCODE -gt 0) { 
        Write-Output "Failed"
    }
    else {    
        Write-Output "Passed"
    } 

【问题讨论】:

  • 在批处理文件中,您可以在命令后添加|| echo failed 并在PowerShell 中查找它,例如.\demo.bat | findstr "failed"
  • 据我所知,那些npm 调用可以从 PoSh 内部运行。您是否尝试过将它们直接放入您的 PoSh 脚本中?

标签: powershell batch-file error-handling


【解决方案1】:

以下代码 sn-p 应返回失败的部分测试计数:

@echo off
set "scriptError=0" 
echo "running  test cases"
call npm run test folder1/file1/validate.test.js
if errorlevel 1 set /a scriptError+=1
call npm run test folder1/file2/validate.test.js
if errorlevel 1 set /a scriptError+=1
exit /B %scriptError%

但是,您可以将 scriptError 变量构造为二进制,以便它显示哪些部分测试失败了,而不仅仅是计数...(提示:如果第一次测试失败,请添加 1,添加 @ 987654324@ 用于第二次测试,添加 4 用于第三次测试,……如果第 n 次测试失败,则添加 2^(n-1)。)

【讨论】:

    【解决方案2】:

    不幸的是,$LASTEXITCODE 将在执行整个脚本时返回错误代码。它被多次覆盖。所以没有办法从powershell处理它。您必须像这样更改批处理文件:

    @echo off
    echo "running  test cases"
    call npm run test folder1/file1/validate.test.js
    if %errorlevel% gtr 0 (echo Failed) else (echo Passed)
    call npm run test folder1/file2/validate.test.js
    if %errorlevel% gtr 0 (echo Failed) else (echo Passed)
    

    在powershell中调用这个,就可以得到rest case的输出了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-23
      • 2011-10-25
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多