Monthly Archive

Categories

PowerShell 6/7 Test-Connection

The PowerShell 6/7 Test-Connection implementation as of PowerShell v6.2.1 and PowerShell v7.0 preview 1 is in my opinion a horrible example of how not to create output. the cmdlet shows each ping and then wraps all of the results in the Replies property so you need to do something like this:

Test-Connection 127.0.0.1 | select -ExpandProperty Replies

 

And on top of all this there’s also a progress bar displayed!

What I really want is a version of test-connection in PowerShell 6/7 that works like test connection does in Windows PowerShell v5.1.

 

There’s a lot of discussion going round in circles about Test-Connection but in the mean time I decided to write my own. I’m only concerned with Windows systems so I can use a CIM class. If I wanted it to work cross-platform I’d need to use a based dot net solution.

function test-connection {
[CmdletBinding()]
param (
[string]$computername,
[int]$count=4,
[switch]$quiet
)

$filter = "Address='$computername'"

$pingresults = 1..$count | ForEach-Object {
$ping = Get-CimInstance -ClassName Win32_PingStatus -Filter $filter
$props = [ordered]@{
Success = if ($ping.StatusCode -eq 0) {$true}else {$false}
Source = $env:COMPUTERNAME
Destination = $ping.Address
IPV4Address = $ping.IPV4Address
Bytes = $ping.BufferSize
Time = $ping.ResponseTime
}

$result = New-Object -TypeName PSobject -Property $props
$result.PSTypeNames[0] = "RSPing"

$result
}

if ($quiet) {
foreach ($pingresult in $pingresults){
$pingresult.Success
}
}
else {
$pingresults
}
}

 

I’ve given the function the name test-connection. If you have a function and a cmdlet with the same name the function takes precedence.

 

The function has three parameters – computername that can take a computer name or an IP address; count = number of pings defaults to 4 and a quiet switch that will return a boolean to indicate success of failure.

 

The work is done by Win32_PingStatus CIM class with a filter that uses the computername for the Address property.

 

The relevant properties are collected into the output object whose type is set to RSPing.

 

If the quiet switch is selected the Success property for each object is displayed otherwise the whole object is output.

 

I don’t want the success property in the full display so I’m going to write a format file to manage the display which I’ll show you next time.

 

PowerShell doesn’t always supply the functionality in the way that you want it but there’s nothing to stop you creating your own version of the command.

Comments are closed.