我有以下代码,试图在其中找到与一天中特定时间有关的值。我在if语句中使用以下for循环。
我已经尝试过,但是对if(条件?)逻辑感到困惑
$currentTime = Get-Date -Format "HH:mm"
$poolProfileWorkdayArray: [
{
"time": "00:02",
"hotAmount": 1,
"coldAmount": 1
},
{
"time": "05:00",
"hotAmount": 2,
"coldAmount": 2
},
{
"time": "09:00",
"hotAmount": 3,
"coldAmount": 3
},
{
"time": "14:21",
"hotAmount": 4,
"coldAmount": 4
}
]
--------------------------------------------------
for ($i = 0; $i -lt $($poolProfileWorkdayArray.count); $i++) {
Write-Output "test for $i : $($poolProfileWorkdayArray[$i])"
if (($currentTime -ge $poolProfileWorkdayArray[$i - 1]) -and ($currentTime -le $poolProfileWorkdayArray[$i])) {
Write-Output $poolProfileWorkdayArray[$i - 1]
$customImageColdVmAmount = $poolProfileWorkdayArray[$i - 1].coldAmount
Write-Output "Cold amount for custom weekDay is : $poolProfileWorkdayArray[$i-1].coldAmount)"
break
}
}
我正在寻找的是,它将遍历循环并检查是数组值与$ customImageColdVmAmount值之间的当前时间。我尝试了一下,发现当前时间是17.30,它不起作用,也不是$ customImageColdVmAmount中的值。如果这里的条件合适,那该怎么办?
答案 0 :(得分:0)
我对您的代码进行了一些更正。但是,对于您的预期输出用例,我可能不清楚,但是您的意思是这个意思。
($currentTime = Get-Date -Format "HH:mm")
# Results
<#
17:39
#>
$poolProfileWorkdayArray = @'
[
{
"time": "00:02",
"hotAmount": 1,
"coldAmount": 1
},
{
"time": "05:00",
"hotAmount": 2,
"coldAmount": 2
},
{
"time": "09:00",
"hotAmount": 3,
"coldAmount": 3
},
{
"time": "18:21",
"hotAmount": 4,
"coldAmount": 4
}
]
'@
($WorkDayArray = $poolProfileWorkdayArray | ConvertFrom-Json)
# Results
<#
time hotAmount coldAmount
---- --------- ----------
00:02 1 1
05:00 2 2
09:00 3 3
18:21 4 4
#>
for ($i = 0; $i -lt $($WorkDayArray.count); $i++)
{
"test for $i : $($WorkDayArray.time[$i])"
if (($currentTime -ge $WorkDayArray.time[$i - 1]) -and ($currentTime -le $WorkDayArray.time[$i]))
{
$WorkDayArray[$i - 1]
$customImageColdVmAmount = $WorkDayArray[$i - 1].coldAmount
"Cold amount for custom weekDay is : $($WorkDayArray[$i-1].coldAmount)"
break
}
}
# Results
<#
test for 0 : 00:02
test for 1 : 05:00
test for 2 : 09:00
test for 3 : 18:21
time hotAmount coldAmount
---- --------- ----------
09:00 3 3
Cold amount for custom weekDay is : 3
#>