header image

Testing connectivity before Invoke-Command

Posted by: | October 24, 2015 Comments Off on 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.

under: PowerShell Basics

Comments are closed.