tags:

views:

81

answers:

2

Hi

I´m totally new to Powershell and wanted to write a script that deletes all non-mp3 files in a directory.

My solution:

get-childitem -Recurse | 
Where-Object {!($_.PSIsContainer)} | 
Where {$_.Extension -ne ".mp3"} | 
remove-item

What can be improved in this statement or could be written in another way. Are there any problems with this statement?

Thank you.

A: 
dir -r -Exclude *.mp3 | ?{ !$_.PSIsContainer } | del
xcud
maybe you meant to use -exclude
Peter Seale
The "-WhatIf" parameter is very handy here, btw. After "unoptimizing" it back to functionally equivalent I'm left with essentially the same one-liner you started with.
xcud
I look at that and think "That's gotta be a single call to 'del'" but getting at the .PSIsContainer property from -Exclude is problematic. Here's an old PowerShell team blog on topic: http://blogs.msdn.com/b/powershell/archive/2009/03/13/dir-a-d.aspx
xcud
+2  A: 

I would use just one Where-Object command:

Get-childitem -Recurse | 
    Where-Object {!$_.PSIsContainer -AND $_.Extension -ne '.mp3'} | 
    Remove-Item -whatIf  

If you're certain that no directories have 'mp3' extension :

Get-childitem -Recurse | Where-Object {$_.Extension -ne '.mp3'} | 
    Remove-Item -whatIf 

Remove -whatIf to delete the files.

Shay Levy
what does -whatIf to?
Patrick Säuerl
Describes what would happen if you executed the command without actually executing the command.
Shay Levy