【问题标题】:Handle Directory Exists Exception处理目录存在异常
【发布时间】:2019-06-25 19:06:36
【问题描述】:

我是 PowerShell 新手。我有一段代码可以检查文件夹“ilalog”是否存在。当我第一次运行这个脚本时,它正在检查文件夹“ilalog”,如果它不存在,它正在创建。当我第二次运行脚本时。我收到以下错误:

具有指定名称 D:\Temp\ilalog 的项目已存在 “完全限定错误 ID: DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand”。

如何处理这个异常

我尝试过使用 try 和 Catch 块

 $rgflder="ilalog"
    [bool]$checkrg=Test-Path D:\Gdump\$rgfolder -PathType Any
    if ( $checkrg -eq $False)
    {
try{
    New-Item -Path "D:\Gdump" -Name "$rgflder" -ItemType "directory"
    }
catch [System.IO.IOException] 
    {
            if ($_.CategoryInfo.Category -eq $resExistErr) {Write-host "Dir Exist"}
} 
}       
else
{
Write-Output "Directory Exists" 
 }

【问题讨论】:

    标签: powershell exception


    【解决方案1】:

    如果您想在根据错误类型采取措施的同时继续处理您的脚本,一个简单的方法是检查$error 变量。也可以选择使用 Trap。

    $error.clear()
    New-Item -Path "D:\Gdump" -Name "$rgflder" -ItemType "directory"
    if ($error[0].Exception.GetType().Fullname -eq 'System.IO.IOException') {
        "Dir Exists"
    }
    else {
        "Dir was created"
    }
    

    如果你想使用try-catch,你需要把你的非终止错误当作终止错误来激活catch块。您可以使用-ErrorAction Stop 来执行此操作。

    try {
        New-Item -Path "D:\Gdump" -Name "$rgflder" -ItemType "directory" -ErrorAction Stop
        }
    catch [System.IO.IOException] 
        {
        "Exception caught!"
        }
    

    或者,您可以通过设置 $ErrorActionPreference = 'Stop' 在会话中管理此操作,这将应用于该会话中的所有命令。

    请记住,传递给-ErrorAction 的值会覆盖$ErrorActionPreference 中的设置。此外,错误操作设置对终止错误没有影响。因此,您不能期望设置 -ErrorAction Continue 并让代码继续处理终止错误。

    许多命令返回的对象可能会或可能不会终止错误。您会发现更多的成功,明确指定何时要抛出终止错误。

    您可以在About Common Parameters 阅读有关错误操作首选项的更多信息。我实际上喜欢 Everything About Exceptions 在 PowerShell 中进行异常处理。

    【讨论】:

    • 嗨@AdminOfThings 感谢您的快速回复,我尝试使用 -ErrorAction Stop ,但由于 DirectoryExists.Exception 脚本仍然停止执行。
    • 如果你不想让代码停止,那么你不应该使用try-catch。你应该省略-erroraction。在New-Item 命令之前运行$error.clear(),查看$error[0] 是否存在。
    • 嗨@AdminOfThings 感谢您的回复,我已经删除了您提到的try-catch 块并放置了 $error.clear() ,但我仍然看到错误 Directory Exist,Microsoft.Powershell.Command
    • 如果你不想看到输出,那么你只需要将你的New-Item命令设置为$null就像$null = New-Item .... 一样
    【解决方案2】:

    为什么不简单地像下面那样做呢?

    $rgflder="ilalog"
    
    # combine the path and foldername
    $rgPath = Join-Path -Path 'D:\Gdump' -ChildPath $rgflder
    
    # test if the folder already exists
    if (Test-Path $rgPath -PathType Container) {
        Write-Output "Directory Exists"
    }
    else {
        # if not, create the new folder
        try {
            $null = New-Item -Path $rgPath -ItemType Directory -ErrorAction Stop
            Write-Output "Created directory '$rgPath'"
        }
        catch {
            # something terrible happened..
            Write-Error "Error creating folder '$rgPath': $($_.Exception.Message)"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 2022-11-14
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      相关资源
      最近更新 更多