2015-07-13 87 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

相關問題