Testing connectivity before Invoke-Command

A question on the forum asked about testing if a remote machine could be reached before using Invoke-Command against it.

The usual way to test if you can reach a remote machine is to ping it

PS> Test-Connection -ComputerName $env:COMPUTERNAME -Quiet

That shows you can reach the machine but it doesn’t mean that you can use Invoke-Command to send a request.

I think a better test is to use Test-WSMan

It will test if the WinRm service is running (won’t test if remoting is enabled)

$computers = “$env:COMPUTERNAME”, ‘NotFound’

foreach ($computer in $computers){
    $target = $computer
    if (Test-WSMan -ComputerName $computer -ErrorAction Ignore) {
        Invoke-Command -ComputerName $computer -ScriptBlock {Get-Service}
    else {
        Write-Warning -Message “Couldn’t connect to $computer”


You can push the output to file or put the unreachable machine names into a file if you need to record them.

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s