Category Archives: a

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.




Run a Powershell script (.ps1) from command line


To run a Powershell script from the command line, batch file or task scheduler, use the following:
powershell -command “. ‘%SCRIPT%'”
Note the double quotes (“) followed by single quotes (‘), and the reverse on the end of the line.
eg:
powershell –command  “. ‘c:maintenancetuesday.ps1′”
To load a custom powershell console, for example the Exchange Management Shell, use the following:
powershell –PSConsoleFile %PSC1% –command “. ‘%SCRIPT%'”
eg:
powershell –PSConsoleFile “c:program filesmicrosoftexchange serverv14binExSchell.psc1” -Command “. ‘c:maintenanceReportMailboxSizeExchange2010.ps1′”