Wednesday, June 24, 2009

Powershell: Delete files containing a string

This is a handy PowerShell snippet. The first line creates a list of files containing a specified string, while the second line will delete each item in the list. For a sanity check, put -whatif after the rm command to see what will happen.


For my first attempt I tried to do the whole operation in one go but PowerShell threw an error. It took a little while for me to realise that the select-string command still had the file open which caused the delete to fail. Putting the list of files in to a variable fixed this quickly.