【问题标题】:Powershell Copy-Item Exit code 1Powershell Copy-Item 退出代码 1
【发布时间】:2018-11-11 12:36:46
【问题描述】:

我有一个脚本,里面有几个我想复制的文件,我这样做或多或少是这样的。

Copy-Item xxx1 yyy1 -Force
Copy-Item xxx2 yyy2 -Force
Copy-Item xxx3 yyy3 -Force
Copy-Item xxx4 yyy4 -Force

等等。

现在,如果没有复制任何文件,我希望此脚本以 1 退出。

提前致谢

【问题讨论】:

    标签: powershell error-handling exit-code copy-item


    【解决方案1】:

    您要求的内容类似于bash 中的set -e 选项,它会在命令发出失败信号时立即退出脚本(条件语句除外)[1]支持>.

    PowerShell 没有这样的选项[2],但你可以模拟它:

    # Set up a trap (handler for when terminating errors occur).
    Trap { 
        # Print the error. 
        # IMPORTANT: -ErrorAction Continue must be used, because Write-Error
        #            itself would otherwise cause a terminating error too.
        Write-Error $_ -ErrorAction Continue
        exit 1 
    }
    
    # Make non-terminating errors terminating.
    $ErrorActionPreference = 'Stop'
    
    # Based on $ErrorActionPreference = 'Stop', any error reported by
    # Copy-Item will now cause a terminating error that triggers the Trap
    # handler.
    Copy-Item xxx1 yyy1 -Force
    Copy-Item xxx2 yyy2 -Force
    Copy-Item xxx3 yyy3 -Force
    Copy-Item xxx4 yyy4 -Force
    
    # Failure of an EXTERNAL PROGRAM must be handled EXPLICITLY,
    # because `$ErrorActionPreference = 'Stop'` does NOT apply.
    foo.exe -bar
    if ($LASTEXITCODE -ne 0) { Throw "foo failed." } # Trigger the trap.
    
    # Signal success.
    exit 0
    

    注意

    • 在 PowerShell 内部,退出代码用于错误处理;它们通常仅在从 PowerShell 调用外部程序时或当 PowerShell / PowerShell 脚本需要向外部世界发出成功与失败信号时才会发挥作用(当从另一个 shell 调用时,例如 Windows 上的 cmdbash在类 Unix 平台上)。

    • PowerShell 的自动 $LASTEXITCODE 变量反映了最近执行的外部程序 / PowerShell 脚本(称为 exit <n>)的退出代码。

    • 通过非零退出代码发出失败信号的外部(控制台/终端)程序调用不会触发trap 块,因此在 sn- p 上面。

    • 除非您明确设置退出代码,否则最后执行的外部程序的退出代码决定了脚本的整体退出代码。

    [1] 请注意,此选项有其批评者,因为关于何时容忍失败以及何时导致脚本中止的确切规则很难记住 - 请参阅http://mywiki.wooledge.org/BashFAQ/105

    [2] this RFC proposal 正在讨论可能增加对它的支持。

    【讨论】:

      【解决方案2】:

      你可以做这样的事情,它会以powershell命令错误的数量退出。

      $errorcount = $error.count
      
      Copy-Item xxx1 yyy1 -Force
      Copy-Item xxx2 yyy2 -Force
      Copy-Item xxx3 yyy3 -Force
      Copy-Item xxx4 yyy4 -Force
      
      exit $error.count - $errorcount
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        • 2019-10-15
        • 2017-12-11
        • 2016-07-11
        相关资源
        最近更新 更多