PowerShell - Most Compact way of “Delete all files from this folder except one”


What is the most compact way of deleting all files from a folder except one file in a PowerShell script. I doesn't matter at all which file is kept, just as long as one is kept.

I'm using the PowerShell 2 CTP.

An amalgamation of all the answers so far...

$fp = "\\SomeServer\SomeShare\SomeFolder"
gci $fp |where {$_.mode -notmatch "d"} |sort creationtime -desc |select -last ((@(gci $fp)).Length - 1) |del

Anybody see any issues with using this? How about the -notmatch part?

By : BuddyJoe


My favorite:

move file to preserve elsewhere
delete all files
move preserved file back
By : Joshua

In PS V2 we added -SKIP to Select so you could do:

dir | where {$_.mode -notmatch "d"} |select -skip 1 |del

how about:

dir $dirName | select -first ((dir $dirName).Length -1) | del

deletes all but the last one.

Edit: A more flexible version, plus you won't have to enter the dir command twice:

$include=$False; dir $dirNam | where {$include; $include=$True;} | del

Note, this does the opposite, it deletes all but the first. It also allows you to add clauses, such as to not act on directories:

$include=$False; dir $dirNam | where {$include -and $_.GetType() -ne [System.IO.DirectoryInfo]; $include=$True;} | del

Edit 2 with regards to excluding directories using the Mode property. I guess that should work provided that the framework does not change the way the mode string is generated (I can't imagine it will). Though I might tighten up the regular expression to:

$_.Mode -notmatch "^d.{4}"

If you are trying to avoid typing, adding a function to your profile is your best bet:

function isNotDir($file) { return $file.GetType() -ne [System.IO.DirectoryInfo];}
dir $dirName | where {isNotDir($_)}
By : zdan

This video can help you solving your question :)
By: admin