powershell - 在 PowerShell 中删除最旧版本的目录

标签 powershell

我有一个目录列表,这些目录的格式类似于版本号,我想找到 N 个最旧的目录并删除它们。例如:

/1.2.3.4
/1.2.3.5
/1.2.3.6

我已经尝试了一些事情,但我似乎无法找到我需要去的地方。

我的第一次尝试是这样的:

ls directory | sort Name | select -first 5 | rm -r

但是我不确定这是否适用于所有情况,因为这会(我认为)进行自然排序。这总是会返回正确的结果吗?

我的下一个想法是我可以使用 System.Version 来进行排序。所以我最终得到了这个:

ls directory | %{[System.Version]$_.Name } | sort | select -first 5 | ???

问题是我不确定如何将目录结果与排序联系起来……最好的方法是什么?

gci\\directory 产生

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        12/19/2011   5:19 PM            1.0.1052.54849
d----        12/19/2011   5:29 PM            1.0.1053.54850
d----        12/19/2011   5:36 PM            1.0.1054.54851
d----        12/20/2011   2:11 PM            1.0.1056.54875
d----        12/12/2011  10:39 AM            1.0.991.54625
d----        12/12/2011  12:08 PM            1.0.992.54627
d----        12/12/2011  12:22 PM            1.0.993.54628
d----        12/12/2011   1:15 PM            1.0.994.54630
d----        12/12/2011   2:45 PM            1.0.996.54636
d----        12/12/2011   3:34 PM            1.0.997.54640
d----        12/12/2011   3:48 PM            1.0.998.54641

gci\\目录 | Sort-Object { $_Name -as [Version] } 产生

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        12/12/2011   1:15 PM            1.0.994.54630
d----        12/12/2011  12:22 PM            1.0.993.54628
d----        12/12/2011   2:45 PM            1.0.996.54636
d----        12/12/2011   3:48 PM            1.0.998.54641
d----        12/12/2011   3:34 PM            1.0.997.54640
d----        12/12/2011  12:08 PM            1.0.992.54627
d----        12/19/2011   5:29 PM            1.0.1053.54850
d----        12/19/2011   5:19 PM            1.0.1052.54849
d----        12/19/2011   5:36 PM            1.0.1054.54851
d----        12/12/2011  10:39 AM            1.0.991.54625
d----        12/20/2011   2:11 PM            1.0.1056.54875

这是网络共享是否重要?我对为什么这不起作用感到困惑......我做了一个快速的健全性检查并在单元测试中创建的版本上执行 Array.Sort 排序正确。

最佳答案

您实际上可以对一个表达式进行排序,这将保留您的原始对象。

Get-ChildItem $path  |
    Sort-Object { $_.Name -as [Version] } |
    Select-Object -Last 1 |
    Remove-Item

会成功的。

希望这会有所帮助,

关于powershell - 在 PowerShell 中删除最旧版本的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8568024/

相关文章:

c# - .NET 枚举类型实际上是可变值类型吗?

powershell - PSCustomObject 数组和 ValueFromPipelineByPropertyName

powershell - 如何使用Powershell在Windows窗体中显示带有GUI的图片框?

azure - 无法从 PowerShell Azure Function 更新 Azure 事件网格合作伙伴主题

powershell - 比MSDOS批处理文件更好?

python - 如何制作一个显示简单加载屏幕的程序?请参阅下面的更多细节

powershell - 在 PowerShell 中使用 Collections.Generic.List[Int] 和 Collections.Generic.List``1[Int] 有区别吗?

c# - RSA公钥解密c#(powershell)

powershell - IF语句仍然被触发

html - 使用 powershell 从 HTML 网站抓取图像链接