在Powershell中的条件语句中使用时间

时间:2019-07-16 15:57:26

标签: powershell time conditional-statements

我试图为在一定条件下运行某些代码奠定基础。但我似乎无法掌握如何增加时间。有Powershell的人吗?

$EndDate不再重要。我只是试图用它来了解Powershell如何使用条件

$StartTime=(Get-Date)

$EndDate=[datetime]”00:00”


if ($StartDate -gt "00:00" -and $StartTime -lt "11:59")
{
Write-Host "It is time to work"
}
else 
{
Write-Host "it is time to go"
}

$StartTime

我的代码现在应该说出运行的时间,但是应该说出工作的时间,因为到目前为止,它只有11:56 AM ET

2 个答案:

答案 0 :(得分:2)

如果要与一天中的时间进行比较,请使用TimeOfDay公开的[datetime] TimeSpan-PowerShell将自动将右侧的"HH:mm"字符串转换为有意义的TimeSpan,与以下内容进行比较:

$StartTime = Get-Date

if($StartTime.TimeOfDay -gt "00:00" -and $StartTime.TimeOfDay -le "12:00"){
    # AM
}
else{
    # PM
}

答案 1 :(得分:0)

这两件事通常是正确的。

(get-date) -gt '00:00'
True

(get-date) -lt '23:59'
True

检查未设置的变量:

set-strictmode -v 1