【问题标题】:In powershell, how to return exit code of a subscript to the calling script在powershell中,如何将下标的退出代码返回给调用脚本
【发布时间】:2015-10-01 05:21:58
【问题描述】:

Powershell: 从脚本调用下标时,如果下标退出失败(即退出代码不为 0),则主脚本仍以退出代码 0 退出,显示为成功。

由于在脚本中执行了下标命令,因此主脚本端没有错误。 如何让主脚本读取下标的退出码,将退出码显示为失败?

我曾尝试在退出下标之前返回值并在主脚本中调用它或使用 $lastexitcode 值,但这些都不起作用。

主脚本:

  • AppendFile.ps1

    function ExitWithCode
    {
        param
        (
            $exitcode
        )
        $host.SetShouldExit($exitcode)
        Write-Host "($exitcode)"
        exit
    }
    #..... Do something
    
    #Calling subscript from main script
    & C:\Testappendfile.ps1
    if ($LASTEXITCODE -ne 0){
        ExitWithCode -exitcode 321
    }
    else {
        ExitWithCode -exitcode 0
    }
    
  • TestAppendFile.ps1

    function ExitWithCode
    {
        param
        (
            $exitcode
        )
        $host.SetShouldExit($exitcode)
        Write-Host "($exitcode)"
        exit
    }
    
    $FileExists = Test-Path C:\Files\check.txt
    If ($FileExists -eq $True){
        ExitWithCode -exitcode 0
    }
    else {
        ExitWithCode -exitcode 321
    }
    

如果文件路径不正确,那么我将进入输出:
(321)
(0)

而不是
(321)
【321】

【问题讨论】:

  • 您是否尝试$error[-1] 来获取会话中生成的最后一条错误消息?任何其他答案都需要您发布代码。

标签: powershell return exit-code subscript


【解决方案1】:
trap { $host.SetShouldExit(-1) }

【讨论】:

  • 如果我没记错的话,这需要在子脚本中使用。但我无法得到结果。我已经在我的两个脚本中使用了 $host.SetShouldExit ($exitcode),所以我在主脚本执行结束时的结果是:退出代码 1 退出代码 0
猜你喜欢
  • 1970-01-01
  • 2011-11-26
  • 2017-10-11
  • 1970-01-01
  • 2021-08-16
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多