Leandre Fouche
Leandre Fouche

Reputation: 33

What can I change in this script to prevent an infinite loop

Here is my Powershell code that when i execute it, it will continually loop while waking up my internal sites

$urlFile = "C:\Users\lfouche\Desktop\url\url.txt"
foreach($site in Get-Content $urlFile){
function WakeUp([string] $url)
{
Write-Host "Waking up $url ..." -NoNewLine
$client = new-object system.net.WebClient
$client.UseDefaultCredentials = $true
$null = $client.OpenRead($url)
$client.Dispose()
Write-Host " Ok"
}
@(
      Get-Content $urlFile
  ) | % { WakeUp $_ }

}

Upvotes: 0

Views: 90

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

Well, your script can generally be improved, however I think the error is that you already iterate over Get-Content $urlFile within your foreach condition and also in the loop. Try this:

# define the wake up function once
function WakeUp
{
    Param
    (
        [string] $url
    )

    Write-Host "Waking up $url ..." -NoNewLine

    $client = new-object system.net.WebClient
    $client.UseDefaultCredentials = $true
    $null = $client.OpenRead($url)
    $client.Dispose()

    Write-Host " Ok"
}

$urlFile = "C:\Users\lfouche\Desktop\url\url.txt"
$sites = Get-Content $urlFile
foreach($site in $sites)
{
    # call wake up for each site
    WakeUp $site
}

Upvotes: 1

Related Questions