windows - 在目录中保留 100 个最新文件 - Windows 脚本移植

标签 windows bash shell file cmd

你好:我在 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),我不想删除文件

最佳答案

我意识到这不像使用 for 循环那样神秘和神奇,但它确实有效。如果您确信将删除正确的文件,请从 Remove-Item cmdlet 中删除 -WhatIf

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

关于windows - 在目录中保留 100 个最新文件 - Windows 脚本移植,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56596691/

相关文章:

windows - CreateFile 无法在 Windows 中打开 HID 设备

bash - 从子 shell 中进行循环控制

Python os.listdir() 不断跳过某些文件?

shell - shell 脚本中 DATE 命令的输出

java - Java 类可以模拟另一个 Windows 用户吗?

python - 如何设置 Git 以将 python 应用程序文件部署到 Ubuntu Server 中?

windows - subprocess.Popen args 的编码问题

bash - 可以/bin/bash -c 将变量导出到父shell

bash - 在 Makefile 中使用 bash 变量

fork 程序的 C++ shell 问题