PowerShell is the most compact way to "Delete all files from this folder except one",

What is the most compact way to delete all files from a folder except one file in a PowerShell script. I have no meaning what file is stored, as long as it is stored.

I am using CTP PowerShell 2.

UPDATE:
Combining 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 

Anyone see any problems with this? What about the -notmatch part?

+3
source share
5 answers

In PS V2, we added -SKIP to Select so you can:

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

+9
source

- , . ,

gci $dirName | select -last ((@(gci $dirName)).Length-1) | del

powershell, . Skip-Count, . , ,

gci $dirName | skip-count 1 | del

: http://blogs.msdn.com/jaredpar/archive/2009/01/13/linq-like-functions-for-powershell-skip-count.aspx

, "rm -re -fo" "del"

EDIT2

( ),

gci $dirName | ?{ -not $_.PSIsContainer } | skip-count 1 | del

PSISContainer .

+4

:

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

, .

: , dir:

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

, , , . , , :

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

2 Mode. , , ( , ). :

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

, - :

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

:

move file to preserve elsewhere
delete all files
move preserved file back
+1

del. -Exclude (dir | sort creationtime -desc) [0] -whatif

This will delete all files except the last.

0
source

Source: https://habr.com/ru/post/1703583/


All Articles