在工作日+营业时间循环

问题描述 投票:2回答:2

我正在编写一个脚本,它只会在M-F 8 AM-5PM期间运行。问题是在它下降8-5或M-F while()循环它只是...不知道如何回到循环。这让我觉得我可能会以错误的角度接近我的剧本。也许有更好的方法来做到这一点。

“做某事”部分是它在5分钟之间比较同一文件之间的文件大小。这用于检查文件是否正在增长/缩小。

# Declare current date/time
$Weekday = [int](Get-Date).DayOfWeek
$hour = [int](Get-Date -Format HH)

while (1 -eq 1) {   # always true
    $Weekday = [int](Get-Date).DayOfWeek
    $hour = [int](Get-Date -Format HH)
    while ($Weekday -ge 1 -and $Weekday -le 5) {  # weekday
        $Weekday = [int](get-date).DayOfWeek    # loop check for current day
        while ($hour -ge 8 -and $hour -le 16) { # 8AM-5PM
            $hour = [int](get-date -format HH)  # loop check for current hour
            # Do Something
        }
        else {
            # Sleep until next business hour
            $date = Get-Date
            $date = $date.AddDays(1)
            $mmddyyy = $date.ToString("MM/dd/yyy")
            $nextDy = New-TimeSpan -End "$mmddyyy 08:00"
            Write-Host "Start sleep timer until next 8AM"
            Start-Sleep -Seconds $nextDy.TotalSeconds
        }
    }
    else {
        # Sleep until next business day
        $date = Get-Date
        while ($Date.DayOfWeek -ne "Monday") {$date = $date.AddDays(1)}
        $mmddyyy = $date.ToString("MM/dd/yyy")
        $nextBu = New-TimeSpan -End "$mmddyyy 08:00"
        Write-Host "Start sleep timer until next Monday 8AM"
        Start-Sleep -Seconds $nextBu.TotalSeconds
    }
}
powershell
2个回答
2
投票
  1. 尝试使用计划任务或服务。
  2. 如果要使用PowerShell脚本,请尝试使用: while ($true) { #WeekDay $Weekday = [int](Get-Date).DayOfWeek #loop check for current day $hour = [int](Get-Date -Format HH) if ($Weekday -le 5 -and $Weekday -ge 1) { while ($hour -ge 8 -and $hour -le 16) { #8AM-5PM $hour = [int](Get-Date -Format HH) #loop check for current hour #Do Something } } $date = Get-Date $date = $date.AddDays(1) $mmddyyy = $date.ToString("MM/dd/yyy") $nextDy = New-TimeSpan -End "$mmddyyy 08:00" Write-Host "Start sleep timer until next 8AM" Start-Sleep -Seconds $nextDy.TotalSeconds }

1
投票

我认为你完全错了。

更好的是你使用像TestFileSizeUtil这样的简单库函数来monitor file size或使用像here所示的WMI:

$query = "Select * from __InstanceModificationEvent WITHIN 5 WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Name='C:\\Logs\\test.log'"

Register-WmiEvent -Query $query -Action {
    Write-Host "Current file size is: " $Event.SourceEventArgs.NewEvent.TargetInstance.FileSize
    $prevSize = $Event.SourceEventArgs.NewEvent.PreviousInstance.FileSize
    $curSize = $Event.SourceEventArgs.NewEvent.TargetInstance.FileSize
    if ($curSize -gt $prevSize) {
        $bytes = $curSize - $prevSize
        Write-Host "File grew by: $bytes bytes"
    } else {
        $bytes = $prevSize - $curSize
        Write-Host "File reduced by: $bytes bytes"
    }
}

然后,如果您的脚本全天运行应该无关紧要。

© www.soinside.com 2019 - 2024. All rights reserved.