首页 > 解决方案 > 在目录中保留 100 个最新文件 - Windows 脚本移植

问题描述

嗨:我在 linux 中有一个 cronjob,将最后 100 个文件保存在一个目录中,现在我需要将它移植到 Windows 上。

我的 linux 工作如下:

# sort by time, 1 per line | get files over 100th | delete those
$ ls -1t \my\path\tmp | tail --lines=+100 | xargs rm -f

它每天运行一次

现在我在做

REM  get files olther than 2D, delete
forfiles /d -2 /p "C:\my\path\tmp" /c "cmd /c Del @path" 

只是删除超过 2 天的文件,但如果总数不是太大(<100),我不想删除文件

标签: windowsbashshellfilecmd

解决方案


我意识到这不像使用 for 循环那样神秘和神奇,但它确实有效。如果您对删除正确的文件感到满意,请-WhatIfRemove-Itemcmdlet 中删除 。

powershell -NoLogo -NoProfile -Command ^
    "Get-ChildItem -File |" ^
    "Sort-Object -Property LastWriteTime -Descending |" ^
    "Select-Object -Skip 100 |" ^
    "Remove-Item -WhatIf"

Powershell 也可以在 Linux 和 Mac 上运行。https://github.com/powershell/powershell


推荐阅读