如何处理复制项异常?

n17*_*911 3 powershell exception-handling

我正在编写使用的PowerShell脚本Copy-Item。我想知道如果Copy-Item无法将文件从源复制到目标时将引发哪种异常?

该链接中,我看不到将抛出哪种异常。

如果发生故障,我想处理异常。

小智 7

在Try-Catch中,将标签“ -errorAction stop”添加到Copy-Item调用中,如下所示。errorAction引发Try-Catch可以处理的错误。

$filepathname = 'valid file path and name'
$dest = '\DoesntExist\'

try
{
    Copy-Item $filepathname $dest  -errorAction stop
    Write-Host "Success"
}
catch
{
    Write-Host "Failure"
}
Run Code Online (Sandbox Code Playgroud)


Ans*_*ers 3

由于 PowerShell 基于 .NET,我希望为CopyTo()CreateSubdirectory()方法定义异常:

但是,在 PowerShell 中,我会简单地不加区别地捕获所有异常(除非您想处理特定场景):

try {
  Copy-Item ...
} catch {
  $exception = $_
  ...
}
Run Code Online (Sandbox Code Playgroud)