Powershell 选择并删除文件夹中的最后一个创建项目 [英] Powershell select and remove last create item in a folder

查看:24
本文介绍了Powershell 选择并删除文件夹中的最后一个创建项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除存储库 c:/test 中的最新文件夹(在一个命令 (Pipeline) 中),但它不起作用

I want to remove the newest folder (in one command (Pipeline)) in the repository c:/test but it doesn't work

Get-ChildItem -Path C:\test -File | Sort-Object -Property CreationTime |
  select * |%{remove-item $_.fullname}

推荐答案

注意:问题是关于删除文件夹,但-File开关是用过的.如果要定位(子)文件夹(目录),则应使用 -Directory,在这种情况下,应将 -Recurse 添加到 Remove-Item 调用以避免在目标文件夹非空时出现确认提示.

Note: The question talks about removing a folder, yet the -File switch is used. If targeting a (sub)folder (directory) is intended, -Directory should be used, and in that case -Recurse should be added to the Remove-Item call to avoid a confirmation prompt if the target folder is non-empty.

Get-ChildItem C:\test -File | 
  Sort-Object -Property CreationTime -Descending | # newest one first
    Select-Object -First 1 |                       # take only the first
      Remove-Item -WhatIf

注意:-WhatIf 通用参数在上面的命令中预览操作.一旦您确定操作会执行您想要的操作,请删除 -WhatIf.

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

PowerShell (Core) 7+ 中,您可以利用Sort-Object 的新 -Top 参数并简化为:

In PowerShell (Core) 7+ you can take advantage of Sort-Object's new -Top parameter and simplify to:

Get-ChildItem C:\test -File | 
  Sort-Object -Property CreationTime -Descending -Top 1 |
    Remove-Item -WhatIf

这篇关于Powershell 选择并删除文件夹中的最后一个创建项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆