【发布时间】: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