powershell - Powershell复制项目退出代码1

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

我有一个脚本,其中包含要复制的几个文件,我或多或少都这样做。

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

等等。

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

提前致谢

最佳答案

您要的内容类似于set -e中的bash选项,该选项会导致脚本在命令发出失败信号时立即退出脚本(条件语句除外)[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上的cmd或类似Unix上的bash平台)。
  • PowerShell的自动$LASTEXITCODE变量反射(reflect)了最近执行的名为exit <n>的外部程序/PowerShell脚本的退出代码。
  • 调用通过非零退出代码发出故障信号的外部(控制台/终端)程序不会触发trap块,因此上面代码段中的显式throw语句。
  • 除非您明确设置退出代码,否则最后执行的外部程序的退出代码将决定脚本的总体退出代码。


  • [1]请注意,此选项有其批评之处,因为难以容忍何时发生故障以及何时导致脚本中止的确切规则-请参阅http://mywiki.wooledge.org/BashFAQ/105

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

    关于powershell - Powershell复制项目退出代码1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53248823/

    相关文章:

    SharePoint 2010,Powershell - 遍历所有文档库,创建 View 并将其设置为默认值

    json - Powershell 两个json内容为什么不一样?

    powershell - 使用响应流使用 Powershell 上传文件

    python - 了解 Pylint E1101 : Instance has no replace member

    asp.net-mvc - 如果自定义重定向重定向到 Controller ,则访问异常

    memory-leaks - _exit() 的危险 - 内存泄漏?

    powershell - 作为 TFS 构建的一部分,仅从 TFS checkin 文件

    javascript - Node.JS - 处理某些类型的 promise 拒绝?

    c - 为什么程序返回的退出代码不是我指定的?

    java - 将调用 System.exit(0);来自主运行垃圾收集之外的对象?