Pat Pat - 1 year ago 142
PowerShell Question

Run PowerShell if statement between business hours

I'm looking to run a conditional statement based on if it's business hours or not. Business hours for us are 08:00 to 17:00. I have the script below, but it's not working.

I'm trying to compare

to the hour number.

I have also tried
((Get-Date).hour -ge 17)
and it still failed.

Any thoughts?

while ($loop -eq 1) {

Write-Host "Running"

# Get last write timestamp
$lastwrite = [datetime](Get-ItemProperty -Path $source -Name LastWriteTime).lastwritetime

if ( ((Get-Date).tostring('%H') -le "8" ) -and ( (Get-Date).tostring('%H') -ge "17" ) ) {
# Do nothing, it is outside of the time window
Write-Host "Nothing to do, outside of business hours"
} elseif (($lastwrite -le (Get-Date).addMinutes(-$ageMinutes)) -and ((Get-Date).tostring('%H') -ge "8" -and (Get-Date).tostring('%H') -le "17")) {
# If it's older than $ageMinutes variable above, send an email
$oldTimestampFound = 1
# Sleep for 4 minutes to not flood inboxes (5 minute sleep total with the while loop)
Write-Host "Alert sent. Sleeping for 4 minutes..."
Start-Sleep -s 300
} elseif (($lastwrite -ge (Get-Date).addMinutes(-$ageMinutes)) -and ($oldTimestampFound -eq 1)) {
$oldTimestampFound = 0
Write-Host "All clear"

Write-Host "Sleeping for 60 seconds..."
Start-Sleep -s 60


I put those
in there to try and debug, but my output is

Sleeping for 60 seconds...

Answer Source

You're formatting the Get-Date wrong, use the -Format HH option for Get-Date Personally I'd set it once as an integer for easy comparisons like this:

[int]$hour = get-date -format HH
If($hour -lt 8 -or $hour -gt 17){ <do nothing> }
    If($lastwrite -le (Get-Date).addMinutes(-$ageMinutes)){ <send email, set oldTimeStampFound flag, and sleep> }
        <Clear oldTimeStampFound flag>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download