Somtimes you have to check the network connection state of the devices you want to connect to. Here are two little functions that might do what you want.
Check a particular host if it is reachable by ICMP:
function Test-HostConnection { param( [Parameter(Mandatory=$true)] [string]$ComputerName ) $result = (Test-NetConnection -ComputerName $ComputerName -WarningAction SilentlyContinue -ErrorAction SilentlyContinue).PingSucceeded; return $result; }
This function returns “false” if the host is unreachable.
Now the function that loops through a list of network devices:
function Test-HostConnections { $retval = $true; $hosts = @("computername1", "computername2", "AndSoOn"); $hosts | % { $result = Test-HostConnection -ComputerName $_; if($result -eq $false) { Write-Host -ForegroundColor Red "Connection to $($_) failed. Please check the network connection."; $retval = $false; } } return $retval; }
It loops through all entries in $hosts, to tell me “ALL” the hosts that are currently not reachable.
So if you don’t want to start your scripting until all the devices are online, here’s how you can do it:
if($(Test-HostConnections) -eq $true) { # your code here }