PowerShell is an incredibly powerful tool that allows system administrators to perform network management tasks with ease. Of course when you’re troubleshooting a system you’re going to want to test connectivity between different systems, and generally test how the network components are responding.

In this article, we will explore how to use PowerShell for doing some of the basic network related tests that you’re going to want to perform. Pinging hosts, testing network connectivity, and scanning ports are all important aspects of understanding what is going on with a system that is having issues. This article is intended for system administrators who are learning PowerShell and are familiar with the basics of network components: That is, I expect you already understand what you’re trying to do, I’m just going to show you how to do those things with PowerShell.

Getting Your Environment Set Up with PowerShell 7 and VS Code

Hey, to follow along with the examples in this article, you need to have PowerShell 7 installed on your system. PowerShell 7 is cross-platform, so it can be used on Windows, macOS, and Linux. We recommend using Visual Studio Code (VSCode) as your editor, as it provides excellent support for PowerShell scripting with syntax highlighting, code completion, and integrated debugging.

Ok, with that out of the way, let’s get into pinging and testing networks with PowerShell

Pinging hosts with PowerShell

Pinging hosts is a fundamental network troubleshooting technique used to test the reachability of a host on an IP network. In PowerShell, you can use the Test-Connection cmdlet to ping hosts and gather information about the network path between your system and the target host.

Basic use of the Test-Connection cmdlet

Here’s how you use the Test-Connection cmdlet to ping a computer.

# Ping a single host 
Test-Connection -TargetName www.example.com

Code examples and use cases for Test-Connection

Here are a few use cases for how you could use Test-Connection in your daily administration and troubleshooting.

Pinging Multiple Computers with PowerShell

# Ping multiple hosts 
$hosts = @("www.example.com", "www.google.com", "www.bing.com") 
foreach ($host in $hosts) { Test-Connection -TargetName $host -Count 1 -Quiet }

The code above shows how you can use Test-Connection to ping multiple hosts. It does them one at a time using a Foreach loop. Every host in the array of hostnames is pinged with Test-Connection.

The Test-Connection parameters used here are:

  • -TargetName: Specifies the target host to ping. In this case, it’s the $host variable.
  • -Count: Defines the number of echo requests to send. Here, it is set to 1, meaning only one ping request is sent to each host.
  • -Quiet: When this switch is used, the cmdlet returns a boolean value (True or False) instead of detailed ping results. If the host is reachable and responds to the ping, the cmdlet returns True; otherwise, it returns False.

Testing Network Latency

In this example, we use Test-Connection to test network latency by measuring the response time for ICMP echo requests (ping) to a target host.

$targetHost = "www.example.com"
$pingCount = 5

$results = Test-Connection -TargetName $targetHost -Count $pingCount
$averageLatency = ($results | Measure-Object -Property ResponseTime -Average).Average
$maxLatency = $results | Sort-Object ResponseTime -Descending | Select -First 1 -ExpandProperty ResponseTime
$minLatency = $results | Sort-Object ResponseTime | Select -First 1 -ExpandProperty ResponseTime

"Average latency to $targetHost: $($averageLatency) ms"
"Fastest response: $($minLatency) ms"
"Slowest response: $($maxLatency) ms"

This script sends 5 ping requests to www.example.com and calculates the average latency based on the response times. It also shows the fastest and slowest response to the host. This information can help troubleshoot issues related to network latency, such as slow website loading or delayed response times in applications.

Test connectivity on multiple ports

This example checks if specific ports are open and accepting connections on a target host. This can help identify firewall or network issues that may be blocking traffic.

$targetHost = "www.example.com"
$ports = @(80, 443, 21)

foreach ($port in $ports) {
    $result = Test-Connection -TargetName $targetHost -Port $port -Count 1 -Quiet
    if ($result) {
        "Port $port is open on $targetHost"
    } else {
        "Port $port is closed on $targetHost"
    }
}

The script checks connectivity on ports 80, 443, and 21 on www.example.com. If a port is open, it displays a message indicating that the port is open; if it’s closed, it displays a message indicating that the port is closed.

This could be used to not just test FTP and Web Servers, but testing a larger set of known ports, like SSH (22) and SQL Server (1433).

Performing a traceroute

You can also use Test-Connection with the -Traceroute switch to trace the network path from the source system to a target host. This can help identify issues related to network routing or intermediate network devices.

$targetHost = "www.example.com"
$tracerouteResults = Test-Connection -TargetName $targetHost -Traceroute

foreach ($result in $tracerouteResults) {
    "Hop $($result.Hop) - $($result.Source) - $($result.ProtocolAddress) - $($result.ResponseTime) ms"
}

This script performs a traceroute to www.example.com and displays the hop number, source IP, destination IP, and response time for each hop in the network path. Traceroute results can really be helpful if you want to identify potential routing problems or network bottlenecks that may affect network performance.

Test network performance with varying buffer sizes

Test-Connection has a great option for testing a network connection with different buffer sizes in order to validate network performance. By comparing the response times for different buffer sizes, you can determine how your network handles larger packets and identify potential performance issues.

$targetHost = "www.example.com"
$bufferSizes = @(32, 512, 1024, 2048)

foreach ($bufferSize in $bufferSizes) {
    $result = Test-Connection -TargetName $targetHost -Count 1 -BufferSize $bufferSize
    "Response time with buffer size $($bufferSize) bytes: $($result.ResponseTime) ms"
}

This script sends a single ping request to www.example.com using four different buffer sizes (32, 512, 1024, and 2048 bytes) and displays the response time for each test. By analyzing the results, you can identify if larger packets experience higher latency or other network performance issues.

Test connectivity to an IPv6 address

Test-Connection can be used to test connectivity to an IPv6 address in a similar way as an IPv4 address. In addition to testing connectivity, this can also help you confirm that your network supports IPv6 connectivity and troubleshoot potential IPv6-related issues.

$targetHostIPv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"

$results = Test-Connection -TargetName $targetHostIPv6 -Ping -Count 3
foreach ($result in $results) {
    "Response from $($result.Address) - $($result.ResponseTime) ms"
}

This script sends three ping requests to an IPv6 address (2001:0db8:85a3:0000:0000:8a2e:0370:7334) and displays the response times for each request. The -Ping switch is used to force the use of ICMP echo requests, even when targeting an IPv6 address. This can help you verify IPv6 connectivity and identify potential issues related to IPv6 addressing or routing.

Testing network connectivity with Test-NetConnection

Test-Connection does a great job of performing network and diagnostic testing. AND… It’s cross-platform, so you can use it in Windows, Linux and Mac. So for me, even though I have a lot of muscle memory with Test-NetConnection I’ve made the switch to using Test-Connection. But Test-NetConnection, which came first and was available in Windows for several versions, does include some detailed diagnostics that keep it handy to know on Windows machines.

Basic use of Test-NetConnection

# Test connectivity to a host on a specific port
Test-NetConnection -ComputerName www.example.com -Port 80

For the basic use, the syntax is the same as using the cross-platform Test-Connection. Even some of the other parameters are the same, so that options like testing for multiple ports works as described above.

# Scan ports on multiple hosts
$hosts = @("www.example.com", "www.google.com")
$portRange = 80..90

foreach ($host in $hosts) {
    foreach ($port in $portRange) {
        Test-NetConnection -ComputerName $host -Port $port
    }
}

So why use Test-NetConnection?

If it’s basically the same as Test-Connection, but it’s Windows-only, what am I missing? Why use Test-NetConnection at all? Great question! And it has some great answers, too.

A big part of it is in the output object. Both Test-Connection and Test-NetConnection give you the same basic details, but the actual objects are quite different.

The objects returned by Test-NetConnection provide more detailed diagnostic information compared to the objects returned by Test-Connection. Some specific advantages of the NetConnectionTestResult objects returned by Test-NetConnection are:

  1. Network interface information: Test-NetConnection returns properties like InterfaceAlias and InterfaceIndex, which provide information about the network interface used for the connection test. This can be helpful when troubleshooting network issues on systems with multiple network interfaces.
  2. Detailed error messages: Test-NetConnection returns more specific error messages in the Diagnosis property when a connection test fails. This can be helpful in identifying the cause of a connectivity issue, such as a closed port or a routing problem.
  3. TCP connection state: When testing TCP connections, Test-NetConnection returns the TcpTestSucceeded property, which is a Boolean value indicating whether the TCP connection test succeeded or failed. Additionally, the TcpState property provides the actual state of the TCP connection, such as “Established” or “Closed,” which can help in understanding the status of a connection more precisely.
  4. Comprehensive output: Test-NetConnection combines the functionality of several cmdlets, such as Resolve-DnsName, Test-Connection, and Get-NetAdapter, into a single output object. This allows you to get a more comprehensive view of the network connection and its related properties without having to use multiple cmdlets and parse their output separately.

So the NetConnectionTestResult objects returned by Test-NetConnection provides more detailed diagnostic information, which can make it easier to identify and troubleshoot network issues on Windows systems.

More Network Management Tasks

In addition to the basic network management tasks covered in this article, PowerShell provides cmdlets for working with DNS records, managing network interfaces, and monitoring network traffic. While we won’t go into detail in this article, I’ll mention them here, and you can explore them more as you continue your PowerShell journey.

  • Working with DNS records: PowerShell provides cmdlets like Resolve-DnsName and Get-DnsClientCache that allow you to resolve DNS names, clear the DNS cache, and perform other DNS-related tasks.
  • Managing network interfaces: You can use cmdlets like Get-NetAdapter, Enable-NetAdapter, and Disable-NetAdapter to manage network interfaces on your system, enabling or disabling them as needed.
  • Monitoring network traffic: PowerShell provides cmdlets such as Get-NetTCPConnection and Get-NetUDPEndpoint that enable you to monitor network traffic and examine the status of TCP and UDP connections on your system.

Best practices for PowerShell network management

As you work with PowerShell for network management tasks, try to keep these good habits in mind:

  • Error handling and validation: Ensure that your scripts include proper error handling and input validation to handle unexpected scenarios gracefully.
  • Automating repetitive tasks: Use PowerShell to automate repetitive network management tasks, saving time and reducing the likelihood of human error.
  • Creating reusable functions and scripts: Encapsulate commonly-used functionality in reusable functions or scripts, making your code more modular and maintainable.

Continuing your PowerShell journey

As you progress in your PowerShell learning, remember the importance of practicing and developing new skills. Consider finding a mentor, enrolling in a course, or exploring additional resources and documentation to expand your knowledge. The more you practice, the more proficient you will become in PowerShell and its various features.

Conclusion

In this article, we have explored using PowerShell for network management tasks such as pinging hosts, testing network connectivity, and scanning ports. As you continue your PowerShell journey, experiment with these techniques and explore more advanced network management tasks. By doing so, you will become a more effective and efficient system administrator, able to leverage the full power of PowerShell to manage your organization’s network infrastructure.