PowerShell: How to Skip Files that Cannot Be Accessed


Occasionally in PowerShell you may receive an error message that tells you a particular file cannot be accessed because it is currently being used by another process.

The easiest way to suppress this error is by using -ErrorAction SilentlyContinue, which tells PowerShell to silently continue the task without displaying an error.

Here is one common way to use this syntax in practice:

Remove-Item "C:\my\path\*" -Recurse -Force -ErrorAction SilentlyContinue

This particular example deletes all files in the path that we specified. If any files are currently being used then PowerShell will simply skip over these files without displaying an error message.

The following example shows how to use this syntax in practice.

Example: How to Skip Files that Cannot Be Accessed in PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\data1

We can use the Get-ChildItem cmdlet to view all files and folders in this directory:

We can see that there are three files in this directory:

  • regions.txt
  • roster.csv
  • schedules.csv

Suppose that we would like to delete all files in this directory but suppose that the file schedules.csv is currently open and being used on our computer.

Suppose we attempt to use the Remove-Item cmdlet with the following syntax to delete each of the files in the directory:

Remove-Item "C:\Users\bobbi\data1\*" -Recurse -Force

The following screenshot shows how to use this syntax in practice:

We receive an error message that tells us schedules.csv cannot be accessed because it is being used by another process.

In order to skip this file when deleting all files in the current directory, we can add the command -ErrorAction SilentlyContinue as follows:

Remove-Item "C:\Users\bobbi\data1\*" -Recurse -Force -ErrorAction SilentlyContinue

The following screenshot shows how to use this syntax in practice:

PowerShell skip files that cannot be accessed

Notice that when we run the Get-ChildItem cmdlet again we can see that all files except schedules.csv have been deleted and we don’t receive any error message this time.

Note: You can find the complete documentation for -ErrorAction in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply