【问题标题】:How handle errors with copy-item如何处理复制项的错误
【发布时间】:2018-12-27 14:51:41
【问题描述】:

我有一个备份脚本,可以将多个文件目录复制到备份位置。不幸的是,并非文件夹中的所有文件都可以访问。历史是什么,它们被归档了,剩下的是一个带有灰色 x 的文件名。当我尝试复制它时,我收到以下消息:

Copy-Item : Access to the path 'E:\Backup\Loc\DO\zOLD_Under Review for NOT USED_keep for now\2006-06\N.doc' is denied.
At C:\Users\me\Documents\powershellFiles\Backup.ps1:13 char:4
+    Copy-Item -Path $SourcePath -Destination $DestinationPath -Force - ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (N.doc:FileInfo) [Copy-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : CopyDirectoryInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand

是的,它抱怨的是 To Location,而不是 From Location。我已经打开了目录/文件,所以它不是只读的,但仍然得到这个。

此外,解决这些复制错误需要很长时间。如果我能避免一开始就尝试复制这些文件,那会快得多。这些文件中可能有 200 个已归档。

但是,我复制的是文件夹,而不是单独复制文件名。有些文件未存档在该文件夹中。没有计划清理它们。我试图确定何时发生错误,但只有在 $error.Exception -ne $null 语句将错误写入屏幕并永远失败后才会到达我的断点(请参阅评论)。

知道如何过滤掉已归档的文件,或者抓取它们并对照数组或列表检查它们,以免收到错误消息吗?我还没有弄清楚如何在它们发生时找到它们,因为它正在复制整个文件夹。

我正在查看error checking during copy-item,但我不知道如何将其应用于我的问题。

这是复制方法:

function CopyFileToFolderUNC($SourcePath, $DestinationPath){
   if(-Not (Test-Path $SourcePath)) 
   {
      $global:ErrorStrings.Add("Exception: No such path, $SourcePath;;  ")
      write-output  "++ Error: An error occured during copy operation. No such path, $SourcePath ++"
   }
   Copy-Item -Path $SourcePath -Destination $DestinationPath -Force -Recurse -errorVariable errors 
   foreach($error in $errors)
   {
        if ($error.Exception -ne $null)
        {
            $global:ErrorStrings.Add("Exception: $($error.Exception);;  ")
            write-output  "++ Error: An error occured during copy operation. Exception: $($error.Exception) ++" #this breakpoint is hit after giving errors on screen and taking a long time/failing to copy files it can't reach
        }
        write-output  "Error: An error occured during copy operation. Exception: $($error.Exception)"
    }
}

这是我根据@theo 建议的最新尝试,但它试图复制我没有测试我可以复制的文件的属性的文件,只是它上面的目录:

function CopyFileToFolderUNC($SourcePath, $DestinationPath, $exclude){
   if(-Not (Test-Path $SourcePath )) #-PathType Container
   {
      $global:ErrorStrings.Add("Exception: No such path, $SourcePath;;  ")
      write-output  "++ Error: An error occured during copy operation. No such path, $SourcePath ++"
   }
   #$tempFileName = [System.IO.Path]::GetFileName($SourcePath)
   #$tempDestFileNamePath = "$DestinationPath\$tempFileName"
   Get-ChildItem -Path $SourcePath -Recurse -Force | ForEach {$_} {
      #test if maybe we are dealing with an off-line file here
      #or use the enum name 'Offline'
      # or use the numeric value: 4096
      #$oldAttribs = $null
      $attr = $_.Attributes.value__
      write-output  "++ $_ $attr ++"
      if (($_.Attributes -eq [System.IO.FileAttributes]::Offline) -or ($_.Attributes.value__ -eq "4096")) {
         $_.Attributes=[System.IO.FileAttributes]::Normal
         #$oldAttribs = $_.Attributes
         #make it a 'normal' file with only the Archive bit set
         #$_.Attributes = [System.IO.FileAttributes]::Archive
         #log that the file was an issue and copy the other ones
         $global:ErrorStrings.Add("Found offline file in backup dir, $_. Logging info and not copying this file. Offline. Please investigate.;;  ")
         write-output  "++ Error: An error occured during copy operation. No such path or file, Offline $_ ++"
      } #if
      elseif(($_.Attributes -eq [System.IO.Fileattributes]::Archive) -or ($_.Attributes.value__ -eq "32")) {
         $global:ErrorStrings.Add("Found offline file in backup dir, $_. Logging info and not copying this file. Archive. Please investigate.;;  ")
         write-output  "++ Error: An error occured during copy operation. No such path or file, Archive $_ ++"
      } #elseif
      elseif(($_.Attributes -eq [System.IO.Fileattributes]::SparseFile) -or ($_.Attributes.value__ -eq "512")) {
         $global:ErrorStrings.Add("Found offline file in backup dir, $_. Logging info and not copying this file. SparseFile. Please investigate.;;  ")
         write-output  "++ Error: An error occured during copy operation. No such path or file, SparseFile $_ ++"
      } #elseif
      elseif(($_.Attributes -eq [System.IO.Fileattributes]::ReparsePoint) -or ($_.Attributes.value__ -eq "1024")) {
         $global:ErrorStrings.Add("Found offline file in backup dir, $_. Logging info and not copying this file. ReparsePoint. Please investigate.;;  ")
         write-output  "++ Error: An error occured during copy operation. No such path or file, ReparsePoint $_ ++"
      } #elseif
      else {

         #the file is not or no longer off-line, so proceed with the copy
         $_ | Copy-Item -Destination $DestinationPath -Force -Recurse -ErrorVariable errors
         foreach($error in $errors)
         {
           if ($error.Exception -ne $null)
           {
               $global:ErrorStrings.Add("Exception: $($error.Exception);;  ")
               write-output  "++ Error: An error occured during copy operation. Exception: $($error.Exception) ++"
           }
           write-output  "Error: An error occured during copy operation. Exception: $($error.Exception)"
         }
      } #else
      #if ($oldAttribs) {
      #   $_.Attributes = $oldAttribs
      #}
   } #Get-ChildItem

例如,我正在测试 \\drive\folder\Forms\C Forms\ 的目录,它说它是一个很好的属性“16”,但该目录中有一个文件试图复制到我的 dest 目录,我看到它具有以下属性:file.pdf Archive、SparseFile、ReparsePoint、Offline。但我没有测试那个文件,我测试属性的最后一件事是它所在的目录。

【问题讨论】:

  • 这让我觉得也许源中的存档文件不是文件......相反,它可能是一个符号链接。我不知道如何告诉Copy-Item 直接忽略它们。但是,您可以运行该命令,收集错误文件名,将它们保存到文件中以备后用。如果您使用Get-ChildItem 构建一个列表发送到Copy-Item,您可以使用保存的文件列表将它们从发送到复制命令的项目中过滤掉。
  • 我想这可能是离线文件。 Explorer 将这些项目显示为灰色 X 叠加层
  • 请仔细看看我的功能。我将 -File 与 Get-Childitem 一起使用。您不应该根据存档位拒绝文件,它们是可以的。没有理由检查[System.IO.FileAttributes] 的属性及其数值。只需选择您觉得舒服的语法即可。顺便说一句:使用Switch 将使代码更简洁,然后使用所有elseif 构造。
  • 另外,第一个if 检查离线位。该测试之后的所有测试都测试另一个属性值,因此如果您想要记录更改错误消息,以便它们实际反映测试。
  • @Theo - 当我执行“Get-ChildItem -Path $SourcePath -File | ForEach-Object”时,它会丢失大部分文件和所有子目录。当我使用“Get-ChildItem -Path $SourcePath -Recurse -Depth 2 | ForEach {$_}”时,它会命中所有文件和子目录。在我检查它们是否可以复制之前,它只是试图复制子目录中的所有文件。

标签: powershell error-handling copy-item


【解决方案1】:

在我看来,您描述的文件是离线文件。
在您的函数中,您可以使用以下方法测试是否是这种情况:

function CopyFileToFolderUNC($SourcePath, $DestinationPath){
    if(-Not (Test-Path $SourcePath)) {
        $global:ErrorStrings.Add("Exception: No such path, $SourcePath;;  ")
        Write-Output  "++ Error: An error occured during copy operation. No such path, $SourcePath ++"
    }

    # test if maybe we are dealing with an off-line file here
    if ((Get-Item -Path $SourcePath).Attributes -band 4096) {  # or use the enum name 'Offline'
        # or use .Net:
        # [System.IO.File]::GetAttributes($SourcePath) -band 4096
        Write-Output  "Did not copy: File '$SourcePath' is currently off-line. "
    }
    else {
        # the file is not off-line, so proceed with the copy
        Copy-Item -Path $SourcePath -Destination $DestinationPath -Force -Recurse -errorVariable errors 
        foreach($error in $errors)  {
            if ($error.Exception) {
                $global:ErrorStrings.Add("Exception: $($error.Exception);;  ")
                Write-Output  "++ Error: An error occured during copy operation. Exception: $($error.Exception) ++" #this breakpoint is hit after giving errors on screen and taking a long time/failing to copy files it can't reach
            }
            Write-Output  "Error: An error occured during copy operation. Exception: $($error.Exception)"
        }
    }
}


编辑

根据您的评论,我了解到该函数不是针对单个文件,而是针对在名为 $SourcePath 的目录中找到的所有文件。

在这种情况下,这里有一个更新的函数应该可以解决问题:

function CopyFileToFolderUNC($SourcePath, $DestinationPath){
    if(-Not (Test-Path $SourcePath -PathType Container)) {
        $global:ErrorStrings.Add("Exception: No such path '$SourcePath'")
        Write-Output  "++ Error: An error occured during copy operation. No such path '$SourcePath' ++"
    }

    Get-ChildItem -Path $SourcePath -File | ForEach-Object {
        # test if maybe we are dealing with an off-line file here
        # or use the enum name 'Offline'
        # or use the numeric value: 4096
        if ($_.Attributes -band [System.IO.FileAttributes]::Offline) {  
            Write-Output  "Did not copy: File '$($_.FullName)' is currently off-line."
        }
        else {
            # the file is not off-line, so proceed with the copy
            $_ | Copy-Item -Destination $DestinationPath -Force -Recurse -ErrorVariable errors 
            foreach($error in $errors)  {
                if ($error.Exception) {
                    $global:ErrorStrings.Add("Exception: $($error.Exception);;  ")
                    Write-Output  "++ Error: An error occured during copy operation. Exception: $($error.Exception) ++"
                }
                Write-Output  "Error: An error occured during copy operation. Exception: $($error.Exception)"
            }
        }
    }
}

如果通过处理文件你的意思是你仍然想复制它们,使用这个代替:

function CopyFileToFolderUNC($SourcePath, $DestinationPath){
    if(-Not (Test-Path $SourcePath -PathType Container)) {
        $global:ErrorStrings.Add("Exception: No such path '$SourcePath'")
        Write-Output  "++ Error: An error occured during copy operation. No such path '$SourcePath' ++"
    }

    Get-ChildItem -Path $SourcePath -File | ForEach-Object {
        # test if maybe we are dealing with an off-line file here
        # or use the enum name 'Offline'
        # or use the numeric value: 4096
        $oldAttribs = $null
        if ($_.Attributes -band [System.IO.FileAttributes]::Offline) {  
            $oldAttribs = $_.Attributes
            # make it a 'normal' file with only the Archive bit set
            $_.Attributes = [System.IO.FileAttributes]::Archive
        }

        # the file is not or no longer off-line, so proceed with the copy
        $_ | Copy-Item -Destination $DestinationPath -Force -Recurse -ErrorVariable errors 
        foreach($error in $errors)  {
            if ($error.Exception) {
                $global:ErrorStrings.Add("Exception: $($error.Exception);;  ")
                Write-Output  "++ Error: An error occured during copy operation. Exception: $($error.Exception) ++"
            }
            Write-Output  "Error: An error occured during copy operation. Exception: $($error.Exception)"
        }

        # if you want the attributes in the original file to be restored, use:
        if ($oldAttribs) {
            $_.Attributes = $oldAttribs
        }
    }
}

请参阅FileAttributes Enum 了解所有可能的属性值。

希望有帮助

【讨论】:

  • 感谢您的好主意!由于 $SourcePath 是一个目录,并且目录中的文件可能处于脱机状态,因此我认为 if/else 不适用于这种情况,包括错误消息的写入输出。任何想法如何处理 $SourcePath 目录中的文件有问题?我不认为有数百个文件,所以我不能将它们单独提供给副本。
  • @Michele 我已经编辑了我的答案以处理$SourcePath 文件夹中的所有文件。干杯!
  • 不幸的是,目录有子目录,但这是一个好的开始。我会用你的建议把我到目前为止所拥有的。也许您知道如何在更深的子目录中测试单个文件。例如,我正在测试 \\\drive\folder\Forms\C Forms\ 的目录,它说它是一个很好的属性“16”,但该目录中有一个文件试图复制到我的dest dir,我看到它具有以下属性:file.pdf Archive、SparseFile、ReparsePoint、Offline。但我没有测试那个文件,我测试属性的最后一件事是它所在的目录。
  • @Michele 好的,将-Recurse 添加到Get-Childitem 命令。至于ReparsePoint:据我了解,这些是指向其他文件或驱动器的链接。我建议你直接跳过这些。
  • 我已经尝试将 -recurse 添加到 Get-Childitem,正如您在我对问题的更新中看到的那样,但它不允许我在复制之前查看子目录中的文件。
猜你喜欢
  • 2014-07-29
  • 2016-01-23
  • 2014-03-29
  • 2014-09-02
  • 2019-06-08
  • 2012-04-25
  • 2013-12-01
  • 1970-01-01
  • 2013-03-15
相关资源
最近更新 更多