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?
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”.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With