如何处理 copy-item 的错误

How handle errors with copy-item

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

Copy-Item : Access to the path 'E:\Backup\Loc\DO\zOLD_Under Review for NOT USED_keep for now06-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。我已经打开了 directory/files 所以它不是只读的,但仍然得到这个。

此外,解决这些复制错误需要很长时间。如果我一开始就可以避免尝试复制这些文件,那会快得多。这些文件中可能有 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”,但该目录中有一个文件正试图复制到我的目标目录,我看到它具有以下属性:file.pdf Archive、SparseFile、ReparsePoint、Offline。但我没有测试那个文件,我最后测试的属性是它所在的目录。

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

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

希望对您有所帮助