Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one delete files in a folder matching a regular expression using PowerShell?

I know a common characteristic of the file names of a number of unwanted files on my Windows computer. How can I remove all of these files from a given folder or folder hierarchy with a single regular expression PowerShell command?

like image 424
Techrocket9 Avatar asked May 20 '14 18:05

Techrocket9


People also ask

How do I delete a file in a directory in PowerShell?

Use the Delete() Method Every object in PowerShell has a Delete() method and you can use it to remove that object. To delete files and folders, use the Get-ChildItem command and use the Delete() method on the output. Here, this command will delete a file called “testdata. txt”.

How do you delete a file that is in use by another program in PowerShell?

Open PowerShell by pressing the Start button and typing PowerShell. Press Enter. Type Remove-Item –path c:\testfolder –recurse and hit Enter. Please replace c:\testfolder with the full path to the folder you wish to delete.

What PowerShell command can Remove a file or item?

In PowerShell, the Remove-Item cmdlet deletes one or more items from the list. It utilizes the path of a file for the deletion process. Using the “Remove-Item” command, you can delete files, folders, variables, aliases, registry keys, etc.

How do you automatically delete files in a folder?

Setting a folder to auto-deletebutton for the folder and select Settings. From the Folder Settings screen scroll down to Automated Actions>Delete or Unshare. Check the Auto-delete this folder on a selected date checkbox and choose a date you want the folder to be deleted.


1 Answers

You can pipe a Get-ChildItem command through a Where-Object filter that accepts a RegEx pattern, and then pipe that into Remove-Item. I think that will get you a faster, and better result than using Select-String. With a command like:

Get-ChildItem $Path | Where{$_.Name -Match "<RegEx Pattern>"} | Remove-Item 

The Name attribute will only match the name of the file or folder, along with a file's extension. It will not match against other things along the path. This will pass a FileInfo object down the pipe, which Remove-Item takes as piped input and will remove the files in question.

If you want to include sub folders of your path you would add the -Recurse switch to your Get-ChildItem command, and it would look like this:

Get-ChildItem $Path -Recurse | Where{$_.Name -Match "<RegEx Pattern>"} | Remove-Item 

If you only want to delete files you can specify that in the Where statement by looking at the FileInfo object's PSIsContainer property and inverting it by prefixing the object with an exclamation point like such:

Get-ChildItem $Path -Recurse | Where{$_.Name -Match "<RegEx Pattern>" -and !$_.PSIsContainer} | Remove-Item 
like image 165
TheMadTechnician Avatar answered Sep 22 '22 16:09

TheMadTechnician