Time Between

Welcome Forums General PowerShell Q&A Time Between

This topic contains 6 replies, has 3 voices, and was last updated by

 
Participant
1 year, 5 months ago.

  • Author
    Posts
  • #72757

    Participant
    Points: 1
    Rank: Member

    We would like to execute something by 9 PM daily on the device and if by change the device is offline by that time and boots up by 7 AM next day, then it should not run the program. So I used the following logic, but could not get the required result

    [int]$h = Get-Date -Format HH

    If($h -lt 20 -or $h -gt 7) then {do something } else {exit out}

    Any help please ?

  • #72761

    Participant
    Points: 81
    Rank: Member
    $Hour24  = (Get-Date).Hour
    if ($Hour24 -gt 21 -or $Hour24 -lt 7) { run task } else { don't run task }
    
  • #72763

    Participant
    Points: 1
    Rank: Member

    This gives me incorrect results. How about using like this ?
    If($h -gt $Afterhr -xor $h -lt $Beforehr)

    • #72766

      Participant
      Points: 81
      Rank: Member

      Can you detail what you mean by incorrect result?

      1..24 | % { 
          $Hour24 = ((Get-Date).AddHours($_)).Hour
          if ($Hour24 -gt 21 -or $Hour24 -lt 7) { "$Hour24 run task" } else { "$Hour24 don't run task" } 
      }
      12 don't run task
      13 don't run task
      14 don't run task
      15 don't run task
      16 don't run task
      17 don't run task
      18 don't run task
      19 don't run task
      20 don't run task
      21 don't run task
      22 run task
      23 run task
      0 run task
      1 run task
      2 run task
      3 run task
      4 run task
      5 run task
      6 run task
      7 don't run task
      8 don't run task
      9 don't run task
      10 don't run task
      11 don't run task
      
  • #72767

    Participant
    Points: 1
    Rank: Member

    Oops my bad. It's working as expected. Thanks once again.

    Also is there a way we can pass the logical operators (-gt, -lt) as a command line argument.

    I am trying the following

    [Parameter(Mandatory=$false)]
    [ValidateSet('-lt','-gt')]
    [string]$LOpert = '-lt',

    If($h $LOpert 21 -or $h $LOpert 7) { run task } else { don't run task }

    Command line is

    DP.ps1 -LOpert -lt

  • #72794

    Participant
    Points: 0
    Rank: Member

    You could use Invoke-Expression:

    [Parameter(Mandatory=$false)]
    [ValidateSet('lt','gt')]
    [string]$LOpert = 'lt'

    If((Invoke-Expression "$h -$LOpert 21 -or $h -$LOpert 7")) { run task } else { don't run task }

  • #73579

    Participant
    Points: 1
    Rank: Member

    Thanks everyone!!!

The topic ‘Time Between’ is closed to new replies.