Test-Connection

PowerShell Cmdlet Deep Dive: Test-Connection

Welcome back to Wahmans PowerShell Blog! Today, we dive into one of the most useful cmdlets for network diagnostics and automation: Test-Connection.

Test-Connection is a PowerShell cmdlet that sends ICMP echo request packets (better known as ping) to one or more computers. It’s a great way to verify network connectivity and diagnose networking issues in scripts or interactively in the console.

Basic Syntax

Test-Connection -ComputerName "hostname or IP"

This sends four ICMP echo requests by default, similar to typing ping hostname in a command prompt.

Use Case Examples

1. Ping a Single Computer (Beginner)

This is the most basic usage. Let’s test connectivity to Google’s DNS server:

Test-Connection -ComputerName 8.8.8.8

This command returns a series of response objects showing whether the remote server responded and how long it took.

2. Ping Multiple Computers (Intermediate)

You can test connectivity to several hosts at once by passing an array:

Test-Connection -ComputerName "server1", "server2", "8.8.8.8"

PowerShell will test each one sequentially and output results individually. This is great for checking availability in a small environment.

3. Silent Ping with Boolean Output (Intermediate)

Use the -Quiet switch when you only care about whether the host responds or not (True/False):

Test-Connection -ComputerName 8.8.8.8 -Count 2 -Quiet

This is useful in scripts where you want to make decisions based on reachability.

4. Advanced Monitoring with Foreach and Logging (Advanced)

Let’s create a script that pings a list of servers and logs offline ones to a file:

$servers = Get-Content -Path "C:\servers.txt"
foreach ($server in $servers) {
    if (-not (Test-Connection -ComputerName $server -Count 2 -Quiet)) {
        "$server is offline" | Out-File -FilePath "C:\offline_servers.log" -Append
    }
}

This automates network checks and helps with documenting outages or troubleshooting network segments.

Final Thoughts

Whether you’re troubleshooting connectivity or building automated checks into your scripts, Test-Connection is a powerful and easy-to-use cmdlet you should always keep in your toolbox.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *