Powershell -跳过无法访问的文件并继续

rvpgvaaj  于 2023-03-18  发布在  Shell
关注(0)|答案(1)|浏览(173)

我试图递归删除所有文件和文件夹内的一个文件夹与Powershell通过:

Foreach ($File in $ListFicher)
            {                  
                if ($?)
                  {
                  try{
                     Remove-Item -force  $File -recurse  -Verbose $ErrorActionPreference = "Continue"
                     }
                     catch  {  write-host "the $File directory can't not deleted"
                     
                           }    
                      }    
            }

我想当他不能删除一个文件,例如他被锁定,他继续并删除其他人,但他没有这样做的时刻,他没有向我显示错误,他继续,但不删除其余的文件。谢谢

deyfvvtc

deyfvvtc1#

这可能看起来有点复杂,但它确实有效!请参阅代码中的注解以了解逻辑。

Clear-Host

#*** Setup ***
$BasePath = "N:\Scripts"
$DeletedFiles    = 0
$NonDeletedFiles = 0
$DeletedDirs     = 0
$NonDeletedDirs  = 0

#Gather all directories under $BasePath
$GCIArgs = @{Path      = "$BasePath"
             Directory = $True
             Recurse   = $True
            }
[System.Collections.ArrayList]$Dirs = (Get-ChildItem @GCIArgs).FullName
[Void]$Dirs.Add("$BasePath")  #Add base path to deletion list!

#Sort dirs longest first to allow deletion in proper order
$SDirs = $Dirs | Sort-Object { $_.length } -Descending

For ($Cntr = 0; $Cntr -lt $SDirs.Count; $Cntr++) {

  $GCIArgs = @{Path = "$($SDirs[$($Cntr)])"
               File = $True
               ErrorAction = "SilentlyContinue"
              }
                $FilesToDel = Get-ChildItem @GCIArgs

  If ($Null -ne $FilesToDel) {
  
    ForEach ($File in $FilesToDel) {
      $RIArgs = @{LiteralPath = "$($File.FullName)"
                  Force       = $True
                  ErrorAction = "Stop"
                 }
  
      Try { 
            Remove-Item @RIArgs
            $DeletedFiles += 1   
          }
      Catch {
              "Could not delete File: $File "
              $NonDeletedFiles += 1
            }
  
    } #End ForEach ($File in $FilesToDel)

  } #End If ($FilesToDel.Count -gt 0)
  
  #Remove the containing Directory!

  Try {
       $RIArgs.LiteralPath = "$($SDirs[$($Cntr)])"
       #Note -Recurse necessary to prevent popup msg reporting
       #     child directories when none exist, not sure why?
       Remove-Item @RIArgs -Recurse
       $DeletedDirs += 1
      }
  Catch {
          "Could not Delete Directory: $($SDirs[$($Cntr)])"
          $NonDeletedDirs += 1
  }              
  
} #End For ($Cntr = 0; $Cntr -lt $SDirs.Count; $Cntr++)

"`nRun Statistics:"
"$DeletedDirs Directories were Deleted"
"$DeletedFiles Files were Deleted"
"$NonDeletedDirs Directories could NOT be Deleted"
"$NonDeletedFiles Files could NOT be Deleted!"

样本输出:

Run Statistics:
135 Directories were Deleted:
2243 Files were Deleted
0 Directories could NOT be Deleted
0 Files could NOT be Deleted!

注意:在我得到错误之前,我收到了关于无法删除的文件和目录的消息。

相关问题