28

With PowerShell, what is the most concise way to delete multiple explicitly named files?

E.g. on *ix it would be:

rm subDir/a.png anotherDir/b.jpg thirdDir/c.gif

I'm currently using:

echo subDir/a.png anotherDir/b.jpg thirdDir/c.gif|rm

But I consider it suboptimal, so I would like to see alternatives.

4 Answers 4

46

You can give PowerShell's rm cmdlet (which is itself an alias for Remove-Item) several files, but you need to separate them with commas.

rm .\subDir\a.png, .\anotherDir\b.jpg, .\thirdDir\c.gif

Check out Get-Help Remove-Item for more details. Or read some documentation on Microsoft's website.

5

This is what I ended up using:

echo subDir/a.png anotherDir/b.jpg thirdDir/c.gif|rm

This uses echo to pass three string arguments to rm (Remove-Item). I believe this implicitly uses Remove-Item's -Path parameter. The documentation notes that "The parameter name ("-Path") is optional" and it accepts pipeline input by value.

1
  • This is helpful for doing a copy/paste of multiple files from Git. Aug 26, 2019 at 16:15
1

Old dog's trick, define an array first. Put your stuff in it, and RM the heck out of it.

$myArray = @("subDir/a.png","subDir/b.png","thirdDir/c.gif")
rm $myArray
0

trick to remove similar extension files using * wildcard.

remove all .png files.

rm ./*.png

remove all .extension files e.g .eslintrc, .gitignore, .stylelintrc.json etc

rm ./.*
2
  • 1
    nice and easy..
    – alexherm
    May 29, 2020 at 17:35
  • 1
    Your answer is correct but needs a caveat IMO. Rm is one of the unforgiving commands you should treat like a weapon and globs/wildcards make it like aiming at a crowd. Do a dry-run, use rm's interactive option, use the tab key and check the expansions, or put together a dummy environment to safely run the command and check the results. You could even rely on backups so you can rm freely without risking data. As an example, this solution (correctly) removes .file.txt.swp generated by Vim to maintain changes to file.txt, but in Windows both files would be hidden and easily overlooked.
    – John P
    Feb 2 at 21:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .