Powershell 选择并删除文件夹中的最后一个创建项目

编程入门 行业动态 更新时间:2024-10-20 09:27:34
本文介绍了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 选择并删除文件夹中的最后一个创建项目

本文发布于:2023-11-12 12:06:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581461.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   项目   夹中   Powershell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!