2015-07-13 88 views
3

Powershell: 从脚本调用脚标时,如果脚标以失败退出(即退出代码不为0),则主脚本为仍退出退出码0,显示为成功。在PowerShell中,如何将脚标的退出代码返回给调用脚本

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

我曾尝试在退出下标之前返回值,并在主脚本中调用它或使用$ 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)

+0

你尝试'$错误[-1]'来获得所产生的最后一个错误消息会议?任何其他答案都需要您发布您的代码。 – JGreenwell

回答

1
trap { $host.SetShouldExit(-1) } 
+0

如果我没有错,这需要在子脚本中使用。但我无法得到结果。我已经在两个脚本中使用了$ host.SetShouldExit($ exitcode),所以我在主脚本执行结束时的结果是:退出代码1退出代码0 – Bawa

相关问题