PowerShell - 最简洁的方法"删除此文件夹中的所有文件,除了一个"

Bud*_*Joe 3 powershell powershell-2.0

删除PowerShell脚本中的一个文件以外的文件夹中所有文件的最简洁方法是什么.我保留哪个文件并不重要,只要保留一个文件.

我正在使用PowerShell 2 CTP.

更新:
到目前为止所有答案的合并...

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

有人看到使用它有任何问题吗?-notmatch部分怎么样?

Jef*_*SFT 9

在PS V2中,我们将-SKIP添加到Select中,以便您可以执行以下操作:

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


Jar*_*Par 5

如果没有任何内置函数,它会有点复杂,因为函数需要处理确定的长度。但你可以这样做,这涉及到查看目录两次

gci $dirName | select -last ((@(gci $dirName)).Length-1) | del
Run Code Online (Sandbox Code Playgroud)

我编写了几个 powershell 扩展,使此类任务变得更加容易。一个例子是 Skip-Count,它允许在管道中跳过任意数量的元素。所以代码可以快速搜索到只看目录一次

gci $dirName | skip-count 1 | del
Run Code Online (Sandbox Code Playgroud)

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

编辑

为了杀死文件夹,请使用“rm -re -fo”而不是“del”

编辑2

为了避免所有文件夹(空或非空),您可以修改代码

gci $dirName | ?{ -not $_.PSIsContainer } | skip-count 1 | del
Run Code Online (Sandbox Code Playgroud)

PSISContainer 成员仅适用于文件夹。