Powershell尝试捕获IOException DirectoryExist

时间:2014-12-16 20:37:54

标签: powershell

我使用电源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

4 个答案:

答案 0 :(得分:2)

如果您希望捕获New-Item电话的例外情况,则需要做两件事:

  1. 默认设置$ErrorActionPreference = "Stop",其值为Continue。如果出现异常,这将使脚本停止。

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

  3. 如果要捕获所有异常,只需使用不带参数的catch

    catch 
    {
        Write-Output "Directory Exists Already"
    }
    

    如果你想捕获一个特定的异常,首先通过检查

    的值找出它是哪一个
    $error[0].Exception.GetType().FullName
    

    在您的情况下,值为:

    System.IO.IOException
    

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

    catch [System.IO.IOException]
    {
        Write-Output "Directory Exists Already"
    }
    

    资料来源:An introduction to Error Handling in Powershell

答案 1 :(得分:0)

我不建议在这种情况下实际捕获错误。虽然这可能是一般的正确行动,但在这种特定情况下,我会做以下事情:

$newFolder = "$copyDrive\$folderDate"

if (-not (Test-Path $newFolder)) {
    New-Item -Path $newFolder -ItemType directory
    Copy-Item $parentDirectory\$userDirectory\$folderName\* $newFolder
} else {
    Write-Output "Directory Exists Already"
}

答案 2 :(得分:0)

如果将-ErrorAction Stop添加到创建目录的行,则可以捕获[System.IO.IOException](而不是[System.IO])。您还应该捕获所有可能发生的其他异常:

try {
   New-Item -Path $copyDrive\$folderDate -ItemType directory -ErrorAction Stop
   Copy-Item $parentDirectory\$userDirectory\$folderName\* $copyDrive\$folderDate -ErrorAction Stop
}

catch [System.IO.IOException] {
   WriteOutput $_.Exception.Message
}

catch {
   #some other error
}

答案 3 :(得分:0)

此外,您可以准确地发现目录存在(不幸的是,文件没有文件存在错误类型)。

$resExistErr=[System.Management.Automation.ErrorCategory]::ResourceExists

try {
        New-Item item -ItemType Directory -ErrorAction Stop
    }
    catch [System.IO.IOException] 
    {
        if ($_.CategoryInfo.Category -eq $resExistErr) {Write-host "Dir Exist"}
    }
相关问题