powershell - 如果整夜运行,PowerShell中的时间检查会不断返回负错误
问题描述
我不小心在错误的时间安排了 GPO 任务,这并没有造成多少麻烦,因此我决定在我的 powershell 脚本中添加时间检查,以确保它们仅在核心工作时间之外运行。我在很久以前的一个文件夹中就有这段代码,我在一个要点上找到了,但不幸的是找不到链接来给予适当的信任。
如果它在白天运行,它可以完美地工作,但是当它在夜间运行时,它会返回一个负 int 错误。
这是以下代码:
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
}
}
}
欢迎所有想法,希望有人能看到我看不到的东西!
谢谢
解决方案
您应该使用适当的时间类型,即TimeSpan,这样比较容易:
[timespan]$start = ($script:WorkingHours -split "-")[0]
[timespan]$end = [timespan]($script:WorkingHours -split "-")[1]
[timespan]$current = (Get-Date).TimeOfDay
# the check
$outsideOperationalWindow = $current -lt $start -and $current -ge $end
推荐阅读
- python - Sage python3 jupyter笔记本
- python - 打印所有托管实例时出现 Boto3 KeyError
- javascript - 使用 express 显示消息
- python - 枚举回馈字母作为值而不是单词
- json - 在 Azure 数据工厂 v2 中对 REST Web 服务使用 JSON 正文查询
- android - “bylazy”在Android-Kotlin中的应用是什么?
- excel - Range.Find 在查找失败时产生错误
- javascript - 将数组转换为没有键的对象
- hibernate - 如何使用 CriteriaQuery API 在 ComponentType 中执行 LEFT_JOIN
- python - running 2 while True 一次循环