如果运行一夜,powershell中的时间检查将始终返回负错误
我意外地在错误的时间安排了一个GPO任务,没有造成太多的麻烦,因此我决定在我的powershell脚本中添加一个时间检查,以确保它们只在核心工作时间之外运行。很久以前,我在一个文件夹中找到了这段代码,但不幸的是,我找不到适当的链接 如果它在白天运行,它工作得很好,但是当时间是夜间时,它返回一个负整数错误 以下是代码:如果运行一夜,powershell中的时间检查将始终返回负错误,powershell,powershell-2.0,Powershell,Powershell 2.0,我意外地在错误的时间安排了一个GPO任务,没有造成太多的麻烦,因此我决定在我的powershell脚本中添加一个时间检查,以确保它们只在核心工作时间之外运行。很久以前,我在一个文件夹中找到了这段代码,但不幸的是,我找不到适当的链接 如果它在白天运行,它工作得很好,但是当时间是夜间时,它返回一个负整数错误 以下是代码: Function TimeCheck { $script:WorkingHours = "18:00-7:00" if ($script
Function TimeCheck {
$script:WorkingHours = "18:00-7:00"
if ($script:WorkingHours -match '^[0-9]{1,2}:[0-5][0-9]- [0-9]{1,2}:[0-5][0-9]$') {
$current = Get-Date
$start = Get-Date ($script:WorkingHours.split("-")[0])
$end = Get-Date ($script:WorkingHours.split("-")[1])
# correct for hours that span overnight
if (($end-$start).hours -lt 0) {
$start = $start.AddDays(-1)
}
# if the current time is past the start time
$startCheck = $current -ge $start
# if the current time is less than the end time
$endCheck = $current -le $end
# if the current time falls outside the window
if ((-not $startCheck) -or (-not $endCheck)) {
write-host "[-] Time is outside operational window"
# sleep until the operational window starts again
$sleepSeconds = ($start - $current).TotalSeconds
if($sleepSeconds -lt 0) {
# correct for hours that span overnight
$sleepSeconds = ($start.addDays(1) - $current).TotalSeconds
}
# sleep until the wake up interval
write-host '[!] sleeping for' $sleepSeconds
Start-Sleep -Seconds $sleepSeconds
}
}
}
欢迎所有想法,希望有人能看到我看不到的东西
谢谢如果你的帖子提到了你创建regex的时间,我很快就写了这几行代码
$start = Get-Date -Hour 18 -Minute 0 -Second 0 -Format HH:mm
$end = Get-Date -Hour 7 -Minute 0 -Second 0 -Format HH:mm
$now = Get-Date -Format HH:mm
if (($now -gt $start) -or ($now -lt $end))
{...}
我建议您从实际的DateTime对象开始,而不是使用字符串操作。它将简化您的代码,并最终变得更加健壮 以下脚本检查当前(日期)时间是否介于给定的开始/结束时间之间
$start = ([DateTime]::ParseExact('18:00', 'HH:mm', $null)).TimeOfDay.TotalSeconds
$end = [DateTime]::ParseExact('07:00', 'HH:mm', $null).TimeOfDay.TotalSeconds
$current = (Get-Date).TimeOfDay.TotalSeconds
if (($start -gt $end) -and (($start -lt $current) -or ($current -lt $end))) {
write-host "[-] Time is in operational window"
} elseif (($start -lt $end) -and (($start -lt $current) -and ($current -lt $end))) {
write-host "[-] Time is in operational window"
} else {
write-host "[-] Time is outside operational window"
}
您应该使用适当的时间类型,即,这使比较更容易:
[timespan]$start=($script:WorkingHours-split“-”)[0]
[timespan]$end=[timespan]($script:WorkingHours-split“-”号“[1]
[timespan]$current=(获取日期)。TimeOfDay
#支票
$outsideOperationalWindow=$current-lt$start-和$current-ge$end