sourcetip

Powershell - 접근할 수 없는 파일 건너뛰기

fileupload 2023. 9. 25. 22:56
반응형

Powershell - 접근할 수 없는 파일 건너뛰기

다음을 통해 Powershell로 폴더 안에 있는 모든 파일과 폴더를 재귀적으로 삭제하려고 합니다.

Remove-Item "C:\Users\user\Desktop\The_folder\*" -Recurse -Force

문제는 실행할 때마다 다음과 같은 메시지가 나타난다는 것입니다.

Cannot remove item C:\Users\user\Desktop\The_folder\Delete: The process cannot access the file 'C:\Users\user\Desktop\The_folder\Delete' because it is being used by another process.

사용 중이기 때문에 액세스할 수 없는 파일을 건너뛰려면 어떻게 해야 합니까?(즉, 사용자가 GUI를 통해 액세스할 수 없는 모든 파일을 건너뛸있는지 묻는 것과 같은 방식)

  • 다음을 시도했지만 오류가 발생했습니다.
    Remove-Item "C:\Users\mstjean\Desktop\The_folder\*" -Recurse -Force -ErrorAction Continue
    
      Remove-Item : Cannot remove item C:\Users\mstjean\Desktop\The_folder\Delete:
        The process cannot access the file 'C:\Users\mstjean\Desktop\The_folder\Delete'
        because it is being used by another process.
    
      At line:1 char:1
        + Remove-Item "C:\Users\mstjean\Desktop\The_folder\*" -Recurse -Force -ErrorAction ...
    
        + CategoryInfo: WriteError: (C:\Users\mstjea...e_folder\Delete:DirectoryInfo) [Remove-Item], IOException
        + FullyQualifiedErrorId:    RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
    

오류 메시지를 억제하고 실행을 계속하려면 다음을 사용해야 합니다.-ErrorAction Ignore아니면-ErrorAction SilentlyContinue.

Get-Help about_CommonParameters:

 -ErrorAction[:{Continue | Ignore | Inquire | SilentlyContinue | Stop |
     Suspend }]
     Alias: ea

     Determines how the cmdlet responds to a non-terminating error
     from the command. This parameter works only when the command generates
     a non-terminating error, such as those from the Write-Error cmdlet.

     The ErrorAction parameter overrides the value of the
     $ErrorActionPreference variable for the current command.
     Because the default value of the $ErrorActionPreference variable
     is Continue, error messages are displayed and execution continues
     unless you use the ErrorAction parameter.

     The ErrorAction parameter has no effect on terminating errors (such as
     missing data, parameters that are not valid, or insufficient
     permissions) that prevent a command from completing successfully.

     Valid values:

         Continue. Displays the error message and continues executing
         the command. "Continue" is the default value.

         Ignore.  Suppresses the error message and continues
         executing the command. Unlike SilentlyContinue, Ignore
         does not add the error message to the $Error automatic
         variable. The Ignore value is introduced in Windows
         PowerShell 3.0.

         Inquire. Displays the error message and prompts you for
         confirmation before continuing execution. This value is rarely
         used.

         SilentlyContinue. Suppresses the error message and continues
         executing the command.

         Stop. Displays the error message and stops executing the
         command.

         Suspend. This value is only available in Windows PowerShell workflows.
         When a workflow runs into terminating error, this action preference
         automatically suspends the job to allow for further investigation. After
         investigation, the workflow can be resumed.

종료 오류가 있는 경우-ErrorAction트래핑이 아니라 직접 시도해보셔야 합니다

다음은 순진한 예입니다.

Get-ChildItem "C:\Users\user\Desktop\The_folder\*" -Recurse -Force `
| Sort-Object -Property FullName -Descending `
| ForEach-Object {
    try {
        Remove-Item -Path $_.FullName -Force -ErrorAction Stop;
    }
    catch { }
}

여기, 제가 사용하고 있습니다.-ErrorAction Stop종료되지 않은 모든 오류를 종료 오류로 바꿉니다.Try모든 종단 오류를 가둘 것입니다.catch그러나 블록이 비어 있으므로 모든 것을 트래핑한 다음 오류 처리를 수행하지 않습니다.스크립트가 자동으로 계속됩니다.이것은 기본적으로 VB스크립트의 것과 맞먹습니다.On Error Resume Next. 파일을 반복해야 하지만 그렇지 않으면 파일을 반복해야 합니다.Remove-Item첫 번째 오류 시 중지됩니다.

내가 가지고 있는 것은Sort-Object저 안에그래서 파이프라인을 통해 들어오는 물건들이 역순으로 되어 있습니다.이렇게 하면 파일 및 하위 디렉토리가 포함된 디렉토리보다 먼저 삭제됩니다.그 방법이 완벽한지 100% 확신할 수는 없지만, 효과가 있을 것 같습니다.그 대안은 정말 지저분합니다.

분명 오류가 발생하거나 삭제되지 않은 것을 출력에서 구별할 방법이 없습니다.우리는 모든 오류를 가두고 그것들을 버리고 있습니다.보통 빈 블록은 정말 나쁜 생각이므로 이 방법을 주의해서 사용하세요!

파일이 열리거나 잠겼는지 실제로 테스트하는 것은 아닙니다.그것은 시간 낭비이기 때문입니다.파일을 삭제할 수 없는 이유와 건너뛸 수 없는 경우는 크게 신경 쓰지 않습니다.파일이 잠겨 있는지 확인하고 조건을 사용하여 파일 삭제를 결정한 다음 파일을 삭제하거나 계속 진행하는 것보다 파일을 삭제하고 장애를 트랩하는 것이 더 쉽고 빠릅니다.

언급URL : https://stackoverflow.com/questions/34274761/powershell-skip-files-that-cannot-be-accessed

반응형