Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell复制项目退出代码1_Powershell_Error Handling_Exit Code_Copy Item - Fatal编程技术网

Powershell复制项目退出代码1

Powershell复制项目退出代码1,powershell,error-handling,exit-code,copy-item,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退出 提前感谢您所要求的类似于bash中的set-e选项,该选项会在命令发出故障信号时立即退出脚本(条件除外)[1] PowerShell没有此类选项[2],但您可以模拟它: #

我有一个脚本和几个文件,我想复制,我这样做或多或少

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

现在,如果没有复制任何文件,我希望此脚本以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上调用
    cmd
    ,或在类Unix平台上调用
    bash

  • PowerShell的automatic
    $LASTEXITCODE
    变量反映了最近执行的名为
    exit
    的外部程序/PowerShell脚本的退出代码

  • 通过非零退出代码向外部(控制台/终端)程序发出故障信号的调用不会触发
    trap
    块,因此在上面的代码段中会出现显式
    throw
    语句

  • 除非显式设置退出代码,否则最后执行的外部程序的退出代码将决定脚本的总体退出代码

[1] 请注意,此选项有其批评者,因为关于何时允许失败以及何时导致脚本中止的确切规则很难记住-请参阅


[2] 正在中讨论可能添加对它的支持。

您可以执行类似的操作,它将随着powershell命令错误数的增加而退出

$errorcount=$error.count
复制项目xxx1 yyy1-强制
复制项目xxx2 YYYY2-强制
复制项目xxx3 YYYY3-强制
复制项目xxx4 YYYY4-强制
退出$error.count-$errorcount