• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Foreach and if else loop

J

Jsimpson

#1
Ok, I am missing something here... I want to do a loop to check for
three things from a ping-host: a reply ("1"), no reply ("0"), and
failed to resolve ("null").

My first try that worked looked like this:

foreach ($comp in get-qadcomputer)
{
if ((ping-host -hostname $comp.name -count 1).Received -eq "1")
{ Write-Host "1"}
elseif ((ping-host -hostname $comp.name -count 1).Received -eq "0")
{Write-Host "0"}
else {Write-Host "null"}
}

The problem with this is it pings each twice. So then I tried this:


foreach ($comp in get-qadcomputer)
{{$result = ping-host -hostname $comp.name -count 1}
if ($result.Received -eq "1") { Write-Host "1"}
elseif ($result.Received -eq "0") {Write-Host "0"}
else {Write-Host "null"}
}

But I am sure my syntax it all wrong. Can someone give me a hand?

Thanks,
Jim
 

My Computer

#2
"Jsimpson" <jsimpson2000@xxxxxx> wrote in message
news:295b6957-1974-4f04-83e0-d016e9495441@xxxxxx

>
> foreach ($comp in get-qadcomputer)
> {{$result = ping-host -hostname $comp.name -count 1}
> if ($result.Received -eq "1") { Write-Host "1"}
> elseif ($result.Received -eq "0") {Write-Host "0"}
> else {Write-Host "null"}
> }
>

You're on the right lines by the looks of it. Try it without the additional
curly brackets eg

foreach ($comp in get-qadcomputer) {
$result = ping-host -hostname $comp.name -count 1
if ($result.Received -eq "1") { Write-Host "1"}
elseif ($result.Received -eq "0") {Write-Host "0"}
else {Write-Host "null"}
}




--
Jon
 

My Computer

J

Jsimpson

#3
On Jun 17, 12:51 pm, "Jon" <Email_Addr...@xxxxxx> wrote:

> "Jsimpson" <jsimpson2...@xxxxxx> wrote in message
>
> news:295b6957-1974-4f04-83e0-d016e9495441@xxxxxx
>
>
>

> > foreach ($comp in get-qadcomputer)
> > {{$result = ping-host -hostname $comp.name -count 1}
> > if ($result.Received -eq "1") { Write-Host "1"}
> > elseif ($result.Received -eq "0") {Write-Host "0"}
> > else {Write-Host "null"}
> > }
>
> You're on the right lines by the looks of it. Try it without the additional
> curly brackets eg
>
> foreach ($comp in get-qadcomputer) {
> $result = ping-host -hostname $comp.name -count 1
> if ($result.Received -eq "1") { Write-Host "1"}
> elseif ($result.Received -eq "0") {Write-Host "0"}
> else {Write-Host "null"}
>
> }
>
> --
> Jon
Doh!! Thank you so much. :)
 

My Computer

Users Who Are Viewing This Thread (Users: 1, Guests: 0)