【问题标题】:Powershell get-childitem excludes a range of datesPowershell get-childitem 不包括一系列日期
【发布时间】:2018-12-21 08:11:17
【问题描述】:

我正在使用 Get-ChildItem 来获取日期不等于当前日期/今天的所有 tomcat 日志文件。我想获取日期不在日期范围内的 tomcat 日志文件。例如最近 7 天的文件名不应列出。

tomcat 日志文件名示例:
catalina.2018-12-21.log
host-manager.2018-12-21.log

$date=Get-Date (get-date).addDays(-0) -UFormat "%Y-%m-%d"
$file=Get-ChildItem "C:\tomcat\logs" -exclude "*$date*"

foreach($files in $file)
{
    Move-Item -Path $files -Destination "C:\expiredlogs"
}

[.....]Get all of the logs filename where date is not in the last 7 days range from "C:\expiredlogs"

有没有什么好的、有效的方法来检索7天前到现在不在范围内的所有文件名?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我假设您只想获取所有文件,而不管它们的名称。到目前为止,您基于文件名本身进行搜索,但您可以基于文件的属性进行搜索。在此示例中,我将获取所有 7 天或更早的文件。

    $files=Get-ChildItem "C:\tomcat\logs" | Where-Object LastWriteTime -gt (Get-Date).AddDays(-7).Date
    
    foreach($file in $files)
    {
        Move-Item -Path $file -Destination "C:\expiredlogs"
    }
    

    上面的代码只会查看文件的写入时间,而不考虑文件名。如果需要,您可以通过应用其他过滤器来进一步限制。

    根据@LotPings 的建议更新

    【讨论】:

    • IMO 对一组文件使用复数 $files 并为当前迭代的文件使用单数 $file 更有意义。您的获取日期将包括当前时间,附加 .Date 或使用 Where-Object LastWriteTime -lt [datetime]::Today
    • 干杯@LotPings!没有看他的代码,我只是用我的过滤器逻辑调整了它。感谢您指出这一点。从现在开始将尝试提升我的游戏:)
    【解决方案2】:

    如果您坚持使用文件名,则需要将名称解析为日期,因为 Get-ChildItem 不知道日期。像这样的东西应该可以解决问题:

    Get-ChildItem "c:\programdata\dgs\cathi\log" | `
    where { ([DateTime]::ParseExact($_.Name.Substring($_.Name.Length-14,10),'yyyy-MM-dd', $null) -lt (Get-Date).addDays(-7))} 
    

    数字14不是一个神奇的数字,它是日期的长度+'.log'。

    【讨论】:

      【解决方案3】:

      上述使用LastWriteTime 的方法是正确的方法。但是如果文件名中有时间戳,过滤可能比Where-Object 更有效,你可以给它数组。

      首先创建一个应排除的日期数组:

      $range =  -3 .. -5 | ForEach-Object { "*$(Get-Date (Get-Date).addDays($_) -UFormat '%Y-%m-%d')*" }
      

      今天返回:

      *2018-12-18*
      *2018-12-17*
      *2018-12-16*
      

      并将其传递给Get-ChildItem

      Get-ChildItem "C:\tomcat\logs" -Exclude $range
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-22
        • 1970-01-01
        • 2020-04-21
        • 2019-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多