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部分怎么样?
在PS V2中,我们将-SKIP添加到Select中,以便您可以执行以下操作:
dir | 其中{$ _.mode -notmatch"d"} | select -skip 1 | del
如果没有任何内置函数,它会有点复杂,因为函数需要处理确定的长度。但你可以这样做,这涉及到查看目录两次
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 成员仅适用于文件夹。
归档时间: |
|
查看次数: |
4400 次 |
最近记录: |