How to code it in powershell script?

Answered How to code it in powershell script?

  • Wednesday, July 04, 2012 3:36 AM
     
     

    I would like to add time condition into following coding.

    Does anyone have any suggestions?

    Thanks in advance for any suggestions

    If current time is > 3 pm and current time is < 6 pm then

    Do {
      ....

     }
     catch { Write-Host "There was an error " }
    } While ($true)

    else

    Do {
      ....

     }
     catch { Write-Host "There was an error " }
    } While ($true)

    end if


    Thanks in advance for any suggestions


    • Edited by oem7110 Wednesday, July 04, 2012 4:30 AM
    •  

All Replies

  • Wednesday, July 04, 2012 6:48 AM
     
     Answered Has Code
    if( ((Get-Date).CompareTo([datetime]"3:00 pm") -gt 0) -and ((Get-Date).CompareTo([datetime]"6:00 pm") -lt 0)){
    do{}while{}
    }
    else{
    do{}while{}
    }

  • Wednesday, July 04, 2012 9:32 AM
     
     Answered Has Code

    A slightly easier alternate method:

    if([datetime]::Now -gt '03:00 PM' -AND [datetime]::Now -lt '06:00 PM'){
      # do this
    }else{
      # do that
    }

    The comparisin is a pure side effect of ho PowerShell type coerci

    The comparison is a pure side effect of ho PowerShell type coercion is applied.  Any comparison of datetime type to anything will always attempt to coerce the object to a date time type so almost any near time string will work.

    Try

    [datetime]::Now -gt '15:00'

    This will compare to a tick count by default:

    [datetime]::Now -gt 644769765129639000

    This will comapre to a day at midnight:
    [datetime]::Now -gt '01/01/2013'


    ¯\_(ツ)_/¯

    • Marked As Answer by oem7110 Wednesday, July 04, 2012 12:37 PM
    •  
  • Wednesday, July 04, 2012 12:25 PM
     
     

    Thanks everyone very much for suggestions


    Thanks in advance for any suggestions



    • Edited by oem7110 Wednesday, July 04, 2012 12:37 PM
    •