关于powershell中不同日期时间的问题



我只需要在工作时间运行代码。首先,我检查时间是低于上午8点还是高于晚上7点,如果没有达到,我会计算第二天的时差,并设置睡眠。

#Run the script on business hours
$hour = [int](Get-Date -Format HH)
If ($hour -le 8 -or $hour -gt 18) { 
$date = Get-Date
$date = $date.AddDays(1)
$mmddyyy = $date.ToString("dd/MM/yyyy")
$nextDy = New-TimeSpan -End "$mmddyyy 08:00"
Start-Sleep -Seconds $nextDy.TotalSeconds
}
#<code to execute. I don't use functions. A very simple script>

我看到的问题是,如果是凌晨1点,脚本要到第二天才能运行,而不是只等待7个小时。

这里有另一种方法来获得"在办公时间内或办公时间外";。它使用CCD_ 2对象的CCD_。[grin]

它的作用。。。

  • 设置常量
  • 生成一个具有所需小时数的datetime对象,用于测试比较
  • 导出当前小时
  • 测试该小时是否在办公时间范围内
  • 将结果输出到屏幕

代码。。。

$StartWorkHour = 8
$EndWorkHour = 19
$OfficeHourRange = $StartWorkHour..$EndWorkHour
$Now = Get-Date -Hour 20
#$Now = Get-Date -Hour 9
$CurrentHour = $Now.Hour
if ($CurrentHour -notin $OfficeHourRange)
{
Write-Host ('The current time [ {0} ] is NOT in office hours.' -f $Now.ToString('HH:mm'))
}
else
{
Write-Warning ('    [ {0} ] is during office hours.' -f $Now.ToString('HH:mm'))
}

输出两个小时设置中的每一个。。。

The current time [ 20:56 ] is NOT in office hours.
WARNING:     [ 09:56 ] is during office hours.
#Run the script on business hours
$hour = [int](Get-Date -Format HH)
If ($hour -le 8 ) {
# Get today at 8am
$businessStart = [datetime]'08:00'
# Get difference timespan between business start and now
$difference = $businessStart - (Get-Date)
# Get number of seconds to wait (rounded up)
$totalSecondsToWait = [System.Math]::Ceiling($difference.TotalSeconds)
Start-Sleep -Seconds $totalSecondsToWait
}
elseif ($hour -gt 18) {
# Get tomorrow at 8am
$businessStart = ([datetime]'08:00').AddDays(1)
# Get difference timespan between business start and now
$difference = $businessStart - (Get-Date)

# Get number of seconds to wait (rounded up)
$totalSecondsToWait = [System.Math]::Ceiling($difference.TotalSeconds)

Start-Sleep -Seconds $totalSecondsToWait
}

这是我的拍摄和日期数学。早上8点之前是另一种情况——我不会在睡眠时间上增加一天。我想你指的是晚上7点,而不是"$hour-gt 18"或下午6点在比较中,"上午8点"one_answers"晚上7点"会自动转换为[日期时间]。

$hour = get-date
if ($hour -le '8am') {
$nextDy = [datetime]'8am' - $hour
start-sleep $nextDy.totalseconds
} elseif ($hour -gt '7pm') {
$nextDy = [datetime]'8am' + '1' <#day#> - $hour
start-sleep $nextDy.totalseconds
}

相关内容

  • 没有找到相关文章

最新更新