I recently answered a SO post about Test-Connection
Powershell script: create loop for ResponseTime
When a Test-Connection
cannot connect it will return a System.Net.NetworkInformation.PingException
which is fine but I would like to record that as an empty object in output instead of skipping over it. I am aware that I could just select
the properties I want and just create a custom object to output on the command line. That is how I approached the linked question but I feel I could do better.
My desire is to have output like this
Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
WYVERN localhost 127.0.0.1 ::1 32 0
failed host 169.254.158.1
WYVERN localhost 127.0.0.1 ::1 32 0
The two returns are proper from Test-Connection
with a dummy line inserted. It has all the properties of a proper return from Test-Connection
but, since it failed, only some of the properties have values. The only approach that I tried to accomplish this was to create another object of a similar type. Note (Test-Connection -Count 1 localhost).GetType().FullName
returned System.Management.ManagementObject
$servers = "10.50.10.100","169.254.54.1"
$servers | ForEach-Object{
Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue
If(!$testconnection){
$blank = New-Object -TypeName System.Management.ManagementObject
$blank.Destination = $_
}
}
Test-Connection
returns more than just a basic System.Management.ManagementObject
. So the problem is that a new-object will not have the same properties and, as a result, $blank.Destination = $_
will fail since "'Destination' cannot be found on this object". I also experimented with Test-Connection -Count 1 127.0.0.1 | gm -MemberType Property
to try and create a property collection that I could use to build my blank object but that was not bearing an fruit. Most likely since I am not doing it right.
FYI
I am hoping to apply this logic in other places in my scripts. While test-connection
is the cmdlet I am dwelling on in this question I am hunting for a broader solution.
Attempt
I have tried, unsuccessfully, something like this but the object are not being outputted together.
$props = @{}
Test-Connection -Count 1 127.0.0.1 | gm -MemberType Property | %{$props.($_.Name) = ""}
$props.destination = "FailedHostAddress"
New-Object -TypeName PSCustomObject -Property $props