Powershell 尝试捕获 IOException DirectoryExist

4 powershell

我正在使用 Power Shell 脚本将一些文件从我的计算机复制到 USB 驱动器。但是,即使我捕获了 System.IO 异常,我仍然在底部收到错误。我如何正确捕获此异常,以便它在我的 Catch 块中显示消息。

CLS

$parentDirectory="C:\Users\someUser"
$userDirectory="someUserDirectory"
$copyDrive="E:"
$folderName="Downloads"
$date = Get-Date
$dateDay=$date.Day
$dateMonth=$date.Month
$dateYear=$date.Year
$folderDate=$dateDay.ToString()+"-"+$dateMonth.ToString()+"-"+$dateYear.ToString();


Try{
     New-Item -Path $copyDrive\$folderDate -ItemType directory
     Copy-Item $parentDirectory\$userDirectory\$folderName\* $copyDrive\$folderDate
   }
Catch [System.IO]
{
    WriteOutput "Directory Exists Already"
}


New-Item : Item with specified name E:\16-12-2014 already exists.
At C:\Users\someUser\Desktop\checkexist.ps1:15 char:9
+         New-Item -Path $copyDrive\$folderDate -ItemType directory
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (E:\16-12-2014:String) [New-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
Run Code Online (Sandbox Code Playgroud)

Mic*_*lli 6

如果要捕获New-Item调用的异常,则需要做两件事:

  1. 设置$ErrorActionPreference = "Stop"在默认情况下它的值Continue。这将使脚本在出现异常时停止。

  2. 捕获正确的异常和/或所有异常

如果你想捕获所有异常,只需使用catch不带参数:

catch 
{
    Write-Output "Directory Exists Already"
}
Run Code Online (Sandbox Code Playgroud)

如果你想捕获一个特定的异常,首先通过检查的值找出它是哪个

$error[0].Exception.GetType().FullName
Run Code Online (Sandbox Code Playgroud)

在你的情况下,价值是:

System.IO.IOException
Run Code Online (Sandbox Code Playgroud)

然后您可以使用此值作为捕获的参数,如下所示:

catch [System.IO.IOException]
{
    Write-Output "Directory Exists Already"
}
Run Code Online (Sandbox Code Playgroud)

值得一读的来源:Powershell 中的错误处理简介