为什么我的 Powershell Runbook 不能正确理解时间?

Why does my Powershell runbook not understand the time properly?

我有带有两个标签的 Azure 实例,PHExempt 为 TRUE 或 FALSE,还有一个名为 OpeningHours 的标签,其中包含一个类似 0900->1730-M->F 的字符串,表示它何时开启和工作。

以下函数会在需要关闭机器时关闭机器,但不会在机器本应打开时将其打开,仅当 运行 来自 Azure powershell 运行书。它 运行 在笔记本电脑上没问题(通常 "it works on my machine" 嗯)。为什么?

  foreach ($box in ($environment | Sort-Object -Property Name)) {
# I don't know why but for some reason $box.Name in a string doesn't swap in, we need to set a display name in the loop
$displayName = $box.Name

$boxOpening = Get-Date -Hour ($box.Tags.OpeningHours.Split("->")[0]).substring(0,2) -Minute ($box.Tags.OpeningHours.Split("->")[0]).substring(2,2)
$boxClosing = (Get-Date -Hour ($box.Tags.OpeningHours.Split("->")[2]).substring(0,2) -Minute ($box.Tags.OpeningHours.Split("->")[2]).substring(2,2))

if ($boxClosing.Hour -lt 12) { #do we close in the morning?
  $boxClosing = $boxClosing.AddDays(1) #tomorrow not today
}

if (($currenttime -gt $boxOpening) -and ($currenttime -lt $boxClosing)) {
  $shouldBeOn = "TRUE"
} else {
  $shouldBeOn = "FALSE"

}


$Name = $box.Name
Write-Host "$Name opens at $boxOpening and closes at $boxClosing, should be on is $shouldBeOn"

if ($shouldBeOn -eq "FALSE") {
  if ($box.Tags.PHExempt -eq "FALSE") {
    if ((Get-AzureRmVM -ResourceGroupName $box.ResourceGroupName -Name $Name -Status | Select-Object -ExpandProperty Statuses `
           | Where-Object { $_.Code -match "PowerState" } | `
           Select-Object -ExpandProperty DisplayStatus) -eq "VM running") {
      Stop-AzureRmVM -Name $box.Name -ResourceGroupName $box.ResourceGroupName -Force
    }
  }
} elseif ($shouldBeOn -eq "TRUE") {
  if ((Get-AzureRmVM -ResourceGroupName $box.ResourceGroupName -Name $Name -Status | Select-Object -ExpandProperty Statuses `
         | Where-Object { $_.Code -match "PowerState" } | `
         Select-Object -ExpandProperty DisplayStatus) -eq "VM deallocated") {

    Start-AzureRmVM -Name $box.Name -ResourceGroupName $box.ResourceGroupName
  }
}

}

时区很烂。

问题确实是 GMT 问题(Shadowzee,如果您添加答案而不是您的评论,我会投票给它正确答案)。如果 GMT 当前与 AEST 相比,通过使用 get-date 并用标签中的时间覆盖时间来计算开启时间和关闭时间基本上是行不通的。日志显示 - 在仔细检查时,没有机器被打开,因为当前时间不在昨天的打开和关闭时间之间。