我想检查文件是否已在9:00 PM到11:00 PM之类的特定时间更新。如果为true,则使用powershell打印“文件已到达”,然后打印“未更新”。
这是我尝试过的:
$file="F:\akku.txt"
$a=(Get-Item $file).LastWriteTime
$b= $a.ToShortTimeString()
$startTime= Get-Date "09:00 PM"
$endTime=Get-Date "11:00 PM"
$b
$startTime -gt $b
$endTime -lt $b
if( $b -gt $startTime.TimeOfDay -and $b -lt $endTime.TimeOfDay )
{
Write-Host "Replication received"
} else{
Write-Host "Replication not received"
}
请告诉我是否还有其他检测文件的方法
答案 0 :(得分:3)
当前代码的一些注意事项。
$b
和以下两行都没用,不确定您在那做什么。
您不需要短时间字符串,因为PowerShell会将它们视为DateTime
对象,因此您可以使用完整时间。例如。 Monday, 19 November 2018 7:53:48 AM
。因此,不需要.TimeOfDay
。
$File = "F:\akku.txt"
$GetFile = (Get-Item $file).LastWriteTime
$StartTime = Get-Date "09:00 PM"
$EndTime = Get-Date "11:00 PM"
if($GetFile -gt $StartTime -and $GetFile -lt $EndTime){
Write-Host "Replication received"
}else{
Write-Host "Replication not received"
}
答案 1 :(得分:1)
这采用略有不同的方法。它会检查一天中的某个小时,以使用标准数字范围查看其是否在所需范围内。
它还假定您实际上想要的日期是昨天昨天,因为今天进行测试之前没有进行测试范围……并且似乎不太可能在2300和2359之间进行测试。 [咧嘴]
# get date with time set @ midnite
$Yesterday = (Get-Date).AddDays(-1).Date
# 9pm = 2100 hours
$UpdateHourRange = 21..23
# comment out the one you DO NOT want to test with [*grin*]
<#
# create a file with the LastWriteTime set to yesterday @ 2200
$FileName = 'C:\temp\IN_Timespan.txt'
$Null = New-Item -Path $FileName -ItemType File -Force
$TargetFile = Get-Item -LiteralPath $FileName
$TargetFile.LastWriteTime = Get-Date -Day ($Yesterday.Day) -Hour 22 -Minute 00 -Second 00
#>
#<#
# create a file with LastWriteTime set to "now"
$FileName = 'C:\temp\OUT_Timespan.txt'
$Null = New-Item -Path $FileName -ItemType File -Force
#>
#$FileName = "$Env:TEMP\Enable1_WordList_File.txt"
$TargetFile = Get-Item -LiteralPath $FileName
if ($TargetFile.LastWriteTime.Date -eq $Yesterday -and
$TargetFile.LastWriteTime.Hour -in $UpdateHourRange)
{
'Update was in the required timespan.'
' LastWriteTime = {0}' -f $TargetFile.LastWriteTime
' Hour = {0}' -f $TargetFile.LastWriteTime.Hour
}
else
{
Write-Warning 'The file was NOT updated in the required timespan.'
Write-Warning (' LastWriteTime = {0}' -f $TargetFile.LastWriteTime)
Write-Warning (' Hour = {0}' -f $TargetFile.LastWriteTime.Hour)
}
“ now”文件的输出...
WARNING: The file was NOT updated in the required timespan.
WARNING: LastWriteTime = 2018-11-18 3:50:19 PM
WARNING: Hour = 15
答案 2 :(得分:0)
越简单越好?
$status = "NotFound " ; gci foo.txt | ? { $_.LastWriteTime.Hour -ge 21 -and $_.LastWriteTime.Hour -lt 23 } | select -First 1 | % { $Status = "Found"}
Write-Host $Status
实际时间范围:
$end = Get-Date -Year 2019 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
$start = Get-Date -Year 2018 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
gci foo.txt | ? { $_.LastWriteTime -ge $start -and $_.LastWriteTime -le $end }
任何一个都可以参数化为脚本。
如果您的文件可能不存在,则可以在此位置添加try / catch,但是您的示例未包含该文件。我假设您简化了发布过程。