查找30天的文件

时间:2017-08-22 18:55:12

标签: powershell

我已经创建了一个脚本来查找一定天数的文件。我正在使用它来查找30天以前的文件,但是如果我需要插入不同的时间,我正试图将其打开。

在您为脚本的这一部分提供您想要的信息后,应该创建一个符合条件的所有文件的文本文件。我可以找到-lt-gt-le-ge的文件,但当我尝试使用-eq时,我得不到任何结果。有关下面列出的部分脚本有什么问题的想法吗?

$Path = Read-Host "What path should I look at?"
$DaysOld = Read-Host "How many days old should the files I'm looking for be?"
$Currentdate = Get-Date
$Targetdate = $Currentdate.AddDays(-$DaysOld).ToString('MM-dd-yyyy')
Write-Host "The target date is $targetdate"
$SourceFolder = $Path
$files = Get-ChildItem $Path -Recurse |
         Where-Object { $_.LastWriteTime -eq $Targetdate } |
         Where-Object { $_.PSIsContainer -eq $false } |
         ForEach-Object { $_.FullName } |
         Out-File $outfileCopy

1 个答案:

答案 0 :(得分:5)

使用-eq的问题是datetime对象是第二个,所以是2017年8月22日上午11:59:27 -eq到8/22/2017 00:00:00 AM?不,不,不是。你可以做的就是使用输出字符串的.ToShortDateString()方法,例如8/22/2017。

$Path = Read-Host "What path should I look at?"
$DaysOld = read-host "How many days old should the files I'm looking for be?"
$Currentdate = get-date
$Targetdate = $currentdate.AddDays(-$daysOLD).ToShortDateString()
Write-Host "The target date is $targetdate"
$SourceFolder = $path
$files = Get-ChildItem $path  -Recurse| Where-Object {$_.lastwritetime.ToShortDateString() -eq $targetdate}|Where-Object {$_.PSIsContainer -eq $false} | ForEach-Object {$_.fullname}| out-file $outfileCopy

这种方法只应在尝试从同一天匹配事物时使用,忽略一天中的时间,并且在查找小于或超过(包括-le和-ge)的内容时不应使用此方法因为它使用字符串评估而不是日期评估。

编辑:多年来我一直在做错,甚至都不知道。非常感谢@Matt指出[DateTime]对象的.date属性,该对象保留了对象类型,但是将时间方面归零。更好的答案:使用.Date属性进行比较,这也应该适用于大于和小于评估。

$Path = Read-Host "What path should I look at?"
$DaysOld = read-host "How many days old should the files I'm looking for be?"
$Currentdate = get-date
$Targetdate = $currentdate.AddDays(-$daysOLD).Date
Write-Host "The target date is $targetdate"
$SourceFolder = $path
$files = Get-ChildItem $path  -Recurse| Where-Object {$_.lastwritetime.Date -eq $targetdate}|Where-Object {$_.PSIsContainer -eq $false} | ForEach-Object {$_.fullname}| out-file $outfileCopy