Need some help adjusting this code so that it will only provide IP addresses that are not pinging and will be exported to a CSV. Currently, it outputs both up and down IP's and I want to clean up some of the clutter.
$ping = (Test-Connection -ComputerName $comp.IPAddress -Count 1 -ErrorAction SilentlyContinue)
if($ping)
{
$status = "Up"
}
else
{
$status = "Down"
}
[pscustomobject]@{
Location = $comp.Location
IP = $comp.IPAddress
Status = $status
}
I have tried manipulating the $status variable but haven't had any luck. I am sure it's something very simple, I am just missing it.
CodePudding user response:
# -Quiet means we just return a boolean true / false value
$ping = Test-Connection -ComputerName ($comp.IPAddress) -Count 1 -ErrorAction SilentlyContinue -Quiet
if(-not $ping)
{
# we only care about when it's down, so move the logic to return our object here
[pscustomobject]@{
Location = $comp.Location
IP = $comp.IPAddress
Status = 'Down'
}
}
CodePudding user response:
Aramus, Welcome to SO!
Test-Connection returns a Null if the connection is down so...
$ping = (Test-Connection -ComputerName $($comp.IPAddress) -Count 1 -ErrorAction SilentlyContinue)
if($Null -ne $ping)
{
$status = "Up"
}
else
{
$status = "Down"
}
Also note the $() around $Comp.IPAddress, this is to insure the parser fetches the IPAddress before running the rest of the command.