在PowerShell中循环时从JSON查找下一个工作日

时间:2019-04-10 10:23:12

标签: json powershell

我从Kayaposoft中找到了一个不错的JSON API,无论给定的一天是工作日(例如4月14日,星期日; isWorkDay: false),该API都会提供true / false值。该API还可以满足我们当地的假期,例如芬兰的Vappu等。

因此,当我尝试在PowerShell中编写脚本(是我的初学者)时,我很快意识到以下代码存在问题。虽然代码可以正常工作,但它不是很实用,它依赖于每个变量两次(一次对其进行设置,一次在循环中)。

有什么方法可以美化此代码?可以使其变得更实用和/或不使用每个变量两次吗?

$date = (Get-Date).AddDays(11)
$jsonDate = $date.ToString('dd-MM-yyyy')

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$jsonRequest = Invoke-WebRequest "https://kayaposoft.com/enrico/json/v2.0/?action=isWorkDay&date=$jsonDate&country=fin" | ConvertFrom-Json

while ($jsonRequest.isWorkDay -ne $true) {

    $date = $date.AddDays(1)
    $jsonDate = $date.ToString('dd-MM-yyyy')

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    $jsonRequest = Invoke-WebRequest "https://kayaposoft.com/enrico/json/v2.0/?action=isWorkDay&date=$jsonDate&country=fin" | ConvertFrom-Json

    Write-Host $jsonDate
    Write-Host $jsonRequest

}

Results:
22-04-2019
@{isWorkDay=False}
23-04-2019
@{isWorkDay=True}

1 个答案:

答案 0 :(得分:1)

类似这样的东西:

$date = (Get-Date)
# not sure if you really need this ?!?
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# do { ... } while (...) - execute at least once
do {

    $jsonDate = $date.ToString('dd-MM-yyyy')    
    $jsonRequest = Invoke-WebRequest "https://kayaposoft.com/enrico/json/v2.0/?action=isWorkDay&date=$jsonDate&country=fin" | ConvertFrom-Json
    $date = $date.AddDays(1)

    Write-Host $jsonRequest
    Write-Host $jsonDate
}
while ($jsonRequest.isWorkDay -ne $true)