使用while-或运算符会导致无限循环

时间:2019-12-04 08:06:22

标签: powershell

您好,我正在尝试在脚本中添加-或运算符,以免使用计数器运行无限脚本,但是如果不使用-或遍历,则无法正常运行,但是如果我添加了程序脚本,运行无限

Import-Module WebAdministration
$server = "server1"
$evtsrc = "AppPool Resurrector"
$loopcounter = 0

if ( [System.Diagnostics.EventLog]::SourceExists($evtsrc) -eq $false){
New-EventLog -LogName Application -Source $evtsrc
}

while((Get-ChildItem IIS:\AppPools | where {$_.state -eq "Stopped"}).count -gt 0 -or ($loopcounter -lt 20))
{   
  $appPools = Get-ChildItem -Path 'IIS:\AppPools' | where {$_.state -eq "Stopped"} | Foreach-Object {$_.Name}
  foreach ($appPoolName in $appPools) {
    Start-WebAppPool $appPoolName
    Write-Host ($appPoolName)
    Start-Sleep -Seconds 10
    $loopcounter++
    if ((Get-WebAppPoolState -Name $appPoolName).Value -eq "Started"){
     Write-EventLog -LogName Application -Message "Start Application Pool `"$appPoolName`" because SMB Client is connected again." -Source $evtsrc -EntryType Warning -EventId 666 -Category 0
    }
else{
    write-Host ("test")
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您应该在此使用-and而不是-or,就像已经评论过Mathias R. Jessen 一样。

此外,我建议使用Write-EventLog cmdlet的参数Splatting,以使代码更具可读性且易于维护。

如下所示:

$loopcounter = 0
$appPools = Get-ChildItem -Path 'IIS:\AppPools' | Where-Object {$_.State -eq "Stopped"}
# as long as there are stopped app pools AND we have not yet reached the max for the loop counter
while ($appPools.Count -gt 0 -and ($loopcounter -lt 20)) {   
    $appPools | Foreach-Object {
        $appPoolName = $_.Name
        Write-Host "Starting '$appPoolName'"
        Start-WebAppPool $appPoolName
        Start-Sleep -Seconds 10   # that's a mighty long wait..
        $loopcounter++
        if ((Get-WebAppPoolState -Name $appPoolName).Value -eq 'Started') {
            $splat = @{
                'LogName'   = 'Application'
                'Message'   = "Start Application Pool '$appPoolName' because SMB Client is connected again."
                'Source'    = $evtsrc
                'EntryType' = 'Warning'
                'EventId'   = 666
                'Category'  = 0
            }
            Write-EventLog @splat
        }
        else{
            write-Host ("test: Counter = $loopcounter")
        }
    }
    # refresh the app pools variable
    $appPools = Get-ChildItem -Path 'IIS:\AppPools' | Where-Object {$_.State -eq "Stopped"}
}

希望有帮助