循环X次

时间:2013-08-28 12:48:02

标签: powershell

我正在处理我的第一个PowerShell脚本,无法确定循环。

我有以下内容,会重复 $ ActiveCampaigns 次数:

Write-Host "Creating $PQCampaign1 Pre-Qualified Report"
Invoke-Item "$PQCampaignPath1\PQ REPORT $PQCampaign1.qvw"
Write-Host "Waiting 1 minute for QlikView to update"
sleep -seconds 60 # Wait 1 minute for QlikView to Reload, create Report and Save.

DO{
    Write-Host "Daily Qlikview Reports"
    Write-Host "Wating for QlikView to create the $PQCampaign1 PQ Report"
    Get-Date
    Write-Host "Checking...."
    sleep -seconds 1
    Write-Host ""
    Write-Host "Not Done Yet"
    Write-Host "Will try again in 5 seconds."
    Write-Host ""
    sleep -seconds 5
}

Until (Test-Path "$PQCampaignPath1\$PQCampaign1 $PQReportName $ReportDate.xlsx" -pathType leaf)

Get-Date
Write-Host "Done with $PQCampaign1 PQ Report. Wait 10 seconds."
sleep -seconds 10

这些参数需要增加每个循环一个:

  • $PQCampaign1(应该成为$PQCampaign2,然后是3,等等。)
  • $PQCampaignPath1(应该成为$PQCampaignPath2,然后是3,等等。)

因此,如果$ActiveCampaigns在某一天设置为8,则需要重复8次,最后一次必须打开$PQCampaign3 $PQCampaignPath8

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:83)

使用:

1..10 | % { write "loop $_" }

输出:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

答案 1 :(得分:29)

这可能是您正在寻找的:

for ($i=1; $i -le $ActiveCampaigns; $i++)
{
  $PQCampaign     = Get-Variable -Name "PQCampaign$i"     -ValueOnly
  $PQCampaignPath = Get-Variable -Name "PQCampaignPath$i" -ValueOnly

  # Do stuff with $PQCampaign and $PQCampaignPath
}

答案 2 :(得分:23)

这是在PowerShell中循环任意次数的简单方法。

它与上面的for循环相同,但对于较新的程序员和脚本编写者来说更容易理解。它使用范围和foreach。范围定义为:

range = lower..upper

$range = 1..10

范围也可以直接在for循环中使用,虽然不是最佳方法,但任何性能损失或额外的处理指令都不会引起注意。解决方案如下:

foreach($i in 1..10){
    Write-Host $i
}

或者在你的情况下:

$ActiveCampaigns = 10
foreach($i in 1..$ActiveCampaigns)
{
    Write-Host $i
    If($i==$ActiveCampaigns){
        // Do your stuff on the last iteration here
    }
}

答案 3 :(得分:1)

See this link。它向您展示了如何在PowerShell中动态创建变量。

这是基本的想法:

使用New-VariableGet-Variable

for ($i=1; $i -le 5; $i++)
{
    New-Variable -Name "var$i" -Value $i
    Get-Variable -Name "var$i" -ValueOnly
}

(取自提供的链接,我不承担代码。)