在营业时间之间运行PowerShell if语句

时间:2014-03-12 22:07:10

标签: powershell

我希望根据是否是营业时间来运行条件声明。我们的营业时间是08:00至17:00。我有下面的脚本,但它不起作用。

我正在尝试将(Get-Date).tostring('%H')与小时数进行比较。

我也试过了((Get-Date).hour -ge 17)但它仍然失败了。

有什么想法吗?

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
        notify
        $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"
        notifyAllClear
    }

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

}

我把那些Write-Hosts放在那里尝试调试,但我的输出是

Running
Sleeping for 60 seconds...

1 个答案:

答案 0 :(得分:5)

您将Get-Date设置为格式错误,请单独使用Get {Date} -Format HH选项我将其设置为整数一次,以便进行简单的比较,如下所示:

[int]$hour = get-date -format HH
If($hour -lt 8 -or $hour -gt 17){ <do nothing> }
Else{
    If($lastwrite -le (Get-Date).addMinutes(-$ageMinutes)){ <send email, set oldTimeStampFound flag, and sleep> }
    Else{
        <Clear oldTimeStampFound flag>
    }
}
相关问题