gpt4 book ai didi

powershell - 如果隔夜运行,PowerShell中的时间检查将始终返回减号错误

转载 作者:行者123 更新时间:2023-12-02 23:16:48 25 4
gpt4 key购买 nike

我意外地设法在错误的时间安排了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
}
}

}
欢迎所有想法,希望有人能看到我看不到的东西!
谢谢

最佳答案

建议您从实际的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"
}

关于powershell - 如果隔夜运行,PowerShell中的时间检查将始终返回减号错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64382900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com