cwheeler33
cwheeler33

Reputation: 115

powershell ping with loop does not return StatusCode

Powershell 4.0 on Windows 7 My IP address is 192.168.0.102 and it does reply to ping from cmd prompt.

I am trying to run the following code which does not behave well:

[int]$intPing = 4
[string]$intNetwork = "192.168.0.102"

for ($i=1;$i -le $intPing; $i++)
{
$strQuery = "select * from win32_pingstatus where address = '" + $intNetwork + $i + "'"
    $wmi = get-wmiobject -query $strQuery
    #"Pinging $intNetwork attempt $i..."
    "Pinging $intNetwork $i ... "
    if ($wmi.statuscode -eq 0)
        {"success"}
    else
        {"error: " + $wmi.StatusCode}

this is an example I found in a book, but is not working for some reason. By supplying my IP it prints an error, but does not return the error code. The same problem without the error code happens if I use a bad IP address. If I use 127.0.0.1 it returns a "success". If I remove the stuff related to the looping it works fine.

The purpose is to learn about looping using "for", so I'm less interested in the best way to do this. I am interested in trying to keep this code as is so that I can learn from it.

So what have I done wrong? And how can I fix it?

Upvotes: 0

Views: 741

Answers (1)

StegMan
StegMan

Reputation: 531

Try changing this

$strQuery = "select * from win32_pingstatus where address = '" + $intNetwork + $i + "'"

to this

$strQuery = "select * from win32_pingstatus where address = '$intNetwork'"

The original contained the increment number, which was causing all of your pings to fail.

Upvotes: 1

Related Questions