Category Archives: Delete

Delete Files Containing a Specific String Using Powershell

I had a number of files, and wanted to delete the files that contained a specific string.  Using Powershell, this can be completed using the following (one line):

get-childitem *.txt | select-string “%STRING_TO_DELETE%” | group path | select name | foreach-object {remove-item $_.name}

Where %STRING_TO_DELETE% is the string that will determine if the file is deleted. EG (one line):


get-childitem *.txt | select-string “SUCCESS” | group path | select name | foreach-object {remove-item $_.name}
 
This will delete any .TXT files in the current directory that contain the string SUCCESS
 
Specifically this was used to remove emails from the mail queue of an Exchange 2003 server that was spamming after a user account was compromised.  I noticed the spam all contained the string “I have urgent feasible plan aligned with our mutual economical interests”.  Using Powershell, I navigated to the mail queue directory, and used the following command:
 

get-childitem *.eml | select-string “I have urgent feasible plan aligned with our mutual economical interests” | group path | select name | foreach-object {remove-item $_.name}

This deleted all the .eml files with the spam string.