Skip to main content
 首页 » 编程设计

powershell之在powershell中,如何将下标的退出代码返回给调用脚本

2025年05月04日163powertoolsteam

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

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

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

主要脚本:

  • 附加文件.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 
    } 
    
  • 测试附加文件.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)

    请您参考如下方法:

    trap { $host.SetShouldExit(-1) }