Delete All Files in Directory in PowerShell

This tutorial will discuss how to delete all files in a directory using PowerShell.

Using Remove-Item cmdlet

To delete all files in a directory:

  • Use the Remove-Item cmdlet.
  • Include asterisk symbol in the file path.

The above command removes all content in the directory C:\test. If there are sub-directories in the location, it will ask you what to do with them.

Answer Y if you want to remove them and N if you want to keep them.

Delete all files in Directory in PowerShell

If you don’t want prompt, you can use -Recurse parameter with Remove-item cmdlet.

Use -Force parameter, in case you want to remove all items that can not be changed such as hidden or read-only files.

You can use Remove-Item to delete different items in PowerShell, such as files, directories, functions, variables, aliases, and registry keys.

Using the Get-ChildItem cmdlet with Remove-Item

Another way of removing all files in a directory is to:

  • Use Get-ChildItem to get all files or directories in a directory.
  • Pipe the command to Remove-Item.

The above command deletes all files found in the directory C:\test.

The -File parameter helps you to get only files. If not used, the command will get directories too.

To recursively delete files in the directory, use the -Recurse parameter with Get-ChildItem.

To recursively delete all files and sub-directories in the directory, use the -Recurse parameter with Get-ChildItem.

It will remove all files in the C:\test directory, including those in its sub-directories.

Using the Delete() method

The object in PowerShell has the Delete() method, which you can use to remove that object.

To delete all files in a directory:

  • Use Get-ChildItem to get the FileInfo object.
  • Apply the Delete method to it.

Delete All Files with Extension PowerShell

To remove all files having extensions, use dot notation in the file path.

It will not delete any files with no extensions.

You can also select files that have the same type of extensions. For instance, to remove only .txt files, you can use this command.

Alternatively, you can use -include parameter to provide extension of files which you want to delete.
Here is the code for the same:

That’s all about how to remove all files in a directory in PowerShell. We also showed you how to delete specific files using the extensions.

We hope this article is helpful for you. If you have any confusion, let us know in the comments.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *