Powershell get-childitem排除日期范围

时间:2018-12-21 08:11:18

标签: powershell

我正在使用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天前至今的所有文件名?

3 个答案:

答案 0 :(得分: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的建议进行了更新

答案 1 :(得分:0)

如果坚持使用文件名,则需要将名称解析为日期,因为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'。

答案 2 :(得分:0)

上面提到的使用const getCat = function(){ if(arrofobj.Type !== 'Switch') arrofobj.ValType'.0' } else { arrofobj.ValType.(arrofobj.val) }; arrofobj.forEach(p => p.CatX = getCat() ); 的方法是正确的方法。但是,如果文件名中有时间戳记,则过滤可能比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