AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / server / 问题 / 526323
Accepted
Jonathan J
Jonathan J
Asked: 2013-07-26 10:56:06 +0800 CST2013-07-26 10:56:06 +0800 CST 2013-07-26 10:56:06 +0800 CST

用于删除最旧文件的 Powershell 脚本(与当前日期无关)

  • 772

我不想“删除超过 X 天的文件”。如果我想这样做,我会从已经为此目的编写的数千个脚本中挑选一个,我不会费心在 ServerFault 上问这样一个微不足道的问题。

我确实想删除特定文件夹中除了最近的 N 个文件之外的所有文件。

背景:远程系统配置为将定期存档文件转储到 Windows 服务器上的共享中。这些文件的命名约定为 YYYYMMDD-hhmm.ext。如果存档过程失败,我不希望清除脚本仅仅因为文件超过这么多天而删除文件。无法将远程系统配置为在归档过程中清除文件。

因此,例如,当脚本运行时,可能有 10 个文件,可能有 7 个文件,文件夹中可能有 5 个文件。我需要始终至少保留最近的 5 个,无论它们多大。

这可以用 PowerShell 完成吗?

编辑:最好忽略与命名约定不匹配的文件或文件夹。不应删除其他文件和文件夹,也不应混淆脚本(导致保留少于 5 个存档文件)。

scripting
  • 6 6 个回答
  • 14240 Views

6 个回答

  • Voted
  1. Best Answer
    Joshua McKinnon
    2013-07-26T20:50:59+08:002013-07-26T20:50:59+08:00

    用法:yourScript.ps1 -Path path\to\run\against [-NumberToSave N]

    param([String]$Path,[Int32]$NumberToSave=5)
    
    $items = Get-ChildItem "$Path\*.ext" |
        Where-Object Name -match "\d\d\d\d\d\d\d\d-\d\d\d\d\.ext" |
        Sort-Object Name -Descending
    
    if ($NumberToSave -lt $items.Count)
    {
        $items[$NumberToSave..($items.Count-1)] | Remove-Item
    }
    

    我不认为这真的比@John 的更好,我只是为了尝试参数、正则表达式而不是使用循环。进行正则表达式匹配确实有可能排除其他与格式不匹配的 .ext 文件(例如 20130504-1200.txt.ext、20.ext),但它是否适用是值得怀疑的。

    我很沮丧地发现如果 $NumberToSave = $items.Count 则需要 if 语句,否则它将不存在。技术上:

    $items[$numberToSave..$items.Count] | Remove-Item 
    

    工作正常(如果您引用超过数组边界,PowerShell 似乎不会出错,它只是处理并忽略它?)但这似乎可能令人困惑。

    • 9
  2. john
    2013-07-26T11:35:42+08:002013-07-26T11:35:42+08:00
    $n = x
    
    $items = Get-ChildItem path_to_folder\*.ext
    
    $items | 
      Sort-Object Name -Descending | 
      Select-Object -Last ($items.count - $n) | 
      Foreach-Object { Remove-Item $_ }
    
    • 5
  3. Jonathan J
    2013-08-01T11:02:30+08:002013-08-01T11:02:30+08:00

    一位朋友提供了这个脚本:

    # Defines how many files you want to keep?
    $Keep = 5
    
    # Specifies file mask
    $FileMask = "*.ext"
    
    # Defines base directory path
    $Path = "F:\path\to\backups\"
    
    # Creates a full path plus file mask value
    $FullPath = $Path + $FileMask
    
    # Creates an array of all files of a file type within a given folder, reverse sort.
    $allFiles = @(Get-ChildItem $FullPath) | SORT Name -descending 
    
    # Checks to see if there is even $Keep files of the given type in the directory.
    If ($allFiles.count -gt $Keep) {
    
        # Creates a new array that specifies the files to delete, a bit ugly but concise.
        $DeleteFiles = $allFiles[$($allFiles.Count - ($allFiles.Count - $Keep))..$allFiles.Count]
    
        # ForEach loop that goes through the DeleteFile array
        ForEach ($DeleteFile in $DeleteFiles) {
    
            # Creates a full path and delete file value
            $dFile = $Path + $DeleteFile.Name
    
            # Deletes the specified file
            Remove-Item $dFile
        }
    }
    
    • 0
  4. splattered bits
    2013-08-02T12:07:30+08:002013-08-02T12:07:30+08:00
    # Get all the items in `C:\Archive`
    Get-ChildItem -Path 'C:\Archive' |
    
        # Skip directories
        Where-Object { -not $_.PsIsContainer } |
    
        # Only get files that match YYYYMMDD-HHMM.ext format
        Where-Object { $_.Name -match '\d{8}-\d{4}.ext' } |
    
        # Sort them by name, from most recent to oldest
        Sort-Object -Descending -Property Name |
    
        # Keep the first five items
        Select-Object -Skip 5 |
    
        Remove-Item -WhatIf
    
    • 0
  5. Get-SomeCoffee
    2022-01-27T07:06:05+08:002022-01-27T07:06:05+08:00

    这适用于我使用 powershell v5.1

    Get-ChildItem -Path C:\Path\To\Logs\BaseName*.log | Sort-Object -Descending | Select-Object -Skip 5 | Remove-Item
    
    • 0
  6. Soviero
    2013-07-26T11:02:51+08:002013-07-26T11:02:51+08:00

    我以前在 Bash 中做过这个,你也许可以将它翻译成 PowerShell。就我个人而言,我是一名 Linux 管理员,我对 Windows/PowerShell 的了解还不够,无法自己这样做。

    #!/bin/bash
    
    # Directory with backups in need of cleaning
    bkps_dir="/opt/bkps/hosting.madyork.com"
    
    # Make sure that there are at least 7 days worth of backups to avoid removing
    #   the only backups left.
    if [ "$(/bin/find "${bkps_dir}" -maxdepth 1 -type d | /usr/bin/wc -l)" -lt 8 ]; then
        echo "Less than 8 backups found!"
        echo "Will not delete anything!"
        echo "Exiting..."
        exit 1
    fi
    
    /bin/find "${bkps_dir}" -maxdepth 1 -type d -mtime +7 -print0 | /usr/bin/xargs -0 /bin/rm -rf
    

    抱歉,我无法提供更多帮助。

    编辑:我也把它放在这里,以防 Linux 管理员需要类似的信息。

    • -1

相关问题

  • 知道任何适用于 Windows 的快速可编写脚本的 ftp 客户端吗?[关闭]

  • 如果同一个任务已经在运行,如何防止计划任务运行?

  • 需要从 Batch For 循环中排除特定结果

  • Bash 脚本:要求脚本以 root 身份运行(或使用 sudo)

  • 从命令行删除旧的(非引导)Windows Vista 目录

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    新安装后 postgres 的默认超级用户用户名/密码是什么?

    • 5 个回答
  • Marko Smith

    SFTP 使用什么端口?

    • 6 个回答
  • Marko Smith

    命令行列出 Windows Active Directory 组中的用户?

    • 9 个回答
  • Marko Smith

    什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同?

    • 3 个回答
  • Marko Smith

    如何确定bash变量是否为空?

    • 15 个回答
  • Martin Hope
    Tom Feiner 如何按大小对 du -h 输出进行排序 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich 什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent 如何确定bash变量是否为空? 2009-05-13 09:54:48 +0800 CST
  • Martin Hope
    cletus 您如何找到在 Windows 中打开文件的进程? 2009-05-01 16:47:16 +0800 CST

热门标签

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve