Table of Contents
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.
1 2 3 |
Remove-Item C:\test\* |
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.
If you don’t want prompt, you can use -Recurse
parameter with Remove-item
cmdlet.
1 2 3 |
Remove-Item C:\test\* -Recurse |
Use -Force
parameter, in case you want to remove all items that can not be changed such as hidden or read-only files.
1 2 3 |
Remove-Item C:\test\* -Recurse -Force |
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
.
1 2 3 |
Get-ChildItem -File C:\test | 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
.
1 2 3 |
Get-ChildItem -File C:\test -Recurse | Remove-Item -Recurse |
To recursively delete all files and sub-directories in the directory, use the -Recurse
parameter with Get-ChildItem
.
1 2 3 |
Get-ChildItem C:\test -Recurse | Remove-Item -Recurse |
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.
1 2 3 |
(Get-ChildItem -File C:\test).Delete() |
Delete All Files with Extension PowerShell
To remove all files having extensions, use dot notation in the file path.
1 2 3 |
Remove-Item C:\test\*.* |
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.
1 2 3 |
Remove-Item C:\test\*.txt |
Alternatively, you can use -include
parameter to provide extension of files which you want to delete.
Here is the code for the same:
1 2 3 |
Remove-Item C:\test\* -Include *.txt |
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.