Search code examples
datetimeintervalspowershell-5.0

Generate a file outside a time interval with date


I'm currently developing a program which is continuously running to create files outside a certain time range. Which means if the current time is outside the starttime and endtime, the file needs to be created.

Here is my code:

$a = get-date -format yyyyMMdd
$b = get-date
while ($true)
{
    $starttime = (get-date "21:00") #9pm today
    $endtime = (get-date "05:00").AddDays(1) #5am next day
    $current = get-date #current time

    ##Something wrong in my checking method, trying to use 'New-timespan' with no luck
    if(($current.TimeOfDay -gt $starttime.TimeOfDay) -and ($current.TimeOfDay -lt $endtime.TimeOfDay)){
        $b = get-date
        Add-Content "$PSScriptRoot\logging_$($a)_tested.txt" "[$b]-> No Need create file"

    } else{
        $b = get-date
        Add-Content "$PSScriptRoot\logging_$($a)_tested.txt" "[$b]-> Starting create file"
    }
    start-sleep -Seconds 30
}

The issue is my code is always in mode "Starting create file". I tried to use New-timespan as well but still hit the same issue.


Solution

  • I found the issue, I had to change the if statement to

    if ($current -lt $starttime -or $current -gt $endtime)