3

除了PowerShell脚本中的一个文件之外,从文件夹中删除所有文件的最紧凑方法是什么。我根本不关心保存哪个文件,只要保存一个即可。

我正在使用 PowerShell 2 CTP。

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

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

有人看到使用这个有什么问题吗?-notmatch 部分怎么样?

4

5 回答 5

9

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

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

于 2009-02-21T16:00:44.437 回答
4

如果没有任何内置函数,这有点令人费解,因为函数需要处理确定的长度。但是您可以这样做,这涉及两次查看目录

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”

编辑2

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

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

PSISContainer 成员仅适用于文件夹。

于 2009-02-20T17:14:55.140 回答
1

怎么样:

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

关于使用 Mode 属性排除目录的编辑 2 。我想这应该可以工作,前提是框架不会改变模式字符串的生成方式(我无法想象它会)。虽然我可能会将正则表达式收紧为:

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

如果您想避免打字,最好向您的个人资料添加功能:

function isNotDir($file) { return $file.GetType() -ne [System.IO.DirectoryInfo];}
dir $dirName | where {isNotDir($_)}
于 2009-02-20T17:04:09.627 回答
1

我的最爱:

move file to preserve elsewhere
delete all files
move preserved file back
于 2009-02-21T16:52:57.493 回答
0

德尔_ -排除 (dir | 排序创建时间 -desc)[0] -whatif

这将删除除最近创建的文件之外的所有文件。

于 2009-02-20T16:55:15.530 回答