【问题标题】:How to loop in Powershell every minute until condition is true?如何每分钟循环一次Powershell,直到条件为真?
【发布时间】:2018-07-07 13:41:30
【问题描述】:

我最近才开始编写 Powershell 脚本。我有一个正在执行负载测试的项目。我运行测试并根据测试结果生成报告。我使用的工具是通过他们的 API 完成的。所以我有 3 个使用 Powershell 脚本发送调用的 Rest API。

第一次调用:启动负载测试,但在配置中设置了多次迭代(可能会运行数小时):

Invoke-RestMethod -Method Post -Uri $StartTestUrl -ContentType "application/json" -OutVariable StartTestResponse -Body $StartTestRequestBody | ConvertTo-Json

第二次调用:获取我们刚刚运行/或仍在运行的负载测试的状态:

Invoke-RestMethod -Method Post -Uri $GetStatusUrl -ContentType "application/json" -OutVariable GetStatusResponse -Body $GetStatusRequestBody | ConvertTo-Json

第三次调用:从完成的测试运行生成报告:

Invoke-RestMethod -Method Post -Uri $GenerateReportUrl -ContentType "application/json" -OutVariable GenerateReportResponse -Body $GenerateReportRequestBody | ConvertTo-Json

目标:我希望能够在 Powershell 中编写一个 DO-WHILE 循环或其他循环,通过每分钟调用第二个 api 来检查响应中的状态“DONE”来检查测试的状态.然后开始第三次通话,因为如果测试未完成,我无法生成报告。

示例:

foreach(var minute in minutes)
{

    // if(status.Done)
    // {
    //   CALL GenerateReport
    // }
    // else
    //{
        //keep checking every minute 
    //}
}

【问题讨论】:

    标签: c# rest powershell loops scripting


    【解决方案1】:

    您可以使用 do-while 循环来执行此操作。在此示例中,假设 $GetStatusResponse 只是一个 $true/$false 值。实际上,您需要修改代码以检查实际的“DONE”消息。

    #1
    Invoke-RestMethod -Method Post -Uri $StartTestUrl -ContentType "application/json" -OutVariable StartTestResponse -Body $StartTestRequestBody | ConvertTo-Json
    
    do{
        # 2
        Invoke-RestMethod -Method Post -Uri $GetStatusUrl -ContentType "application/json" -OutVariable GetStatusResponse -Body $GetStatusRequestBody | ConvertTo-Json
    
        if($GetStatusResponse -eq $False){
            Start-Sleep -Seconds 60
        }
    
    }while($GetStatusResponse -eq $False)
    
    # 3
    Invoke-RestMethod -Method Post -Uri $GenerateReportUrl -ContentType "application/json" -OutVariable GenerateReportResponse -Body $GenerateReportRequestBody | ConvertTo-Json
    

    【讨论】:

    • 在我们得到 $GetStatusResponse 的 True 响应之前,这是否会持续运行每一分钟?
    • @Hashim77 是的。对于第二次通话。条件$GetStatusResponse -eq $False 被简化;您可能必须修改它以适合您的代码。
    • 对,一旦第二次调用被调用,我就会得到这样的响应:{ "d": { "ApiKey": "#####", "Status": "DONE" } }
    • 如果没有DONE,需要1分钟后重新检查。所以我假设,我需要从响应正文中提取状态并像 while($GetStatusResponse.Status eq "Done") 一样检查它?
    • @Hashim77 没错!除了你想要-ne,如“在状态未完成时继续运行”。
    【解决方案2】:

    开始-睡眠-秒 60

    将暂停执行 1 分钟

    MS link to cmdlet

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2013-12-07
      相关资源
      最近更新 更多