1
votes

I want to get the ip of some devices. Some of them are unreachable. If PowerShell wants to get the ip of an unreachable device it terminates the whole Script. I thought about catching the exception. But i could not find anything about how to catch "Host is unknown". I don't know much about exceptions i tried this but of course it does not work:

` try {
    $IPClient = Test-Connection $name -Count 1
    $IPv4 = $IPClient.IPV4Address.IPAddressToString 
    } catch {
    $IPv4 = "Could not find $name"
 }`

If PowerShell finds an not reachable device it terminate the whole Script. How can i catch this so my List of $namecontinues and may fill the Variable with "no device found with $name" or something like that?

1

1 Answers

2
votes

Test-Connection is throwing a 'non-terminating' exception, which catch doesn't handle. To force it to become 'terminating' (and hence handled by catch), use the -ErrorAction parameter:

try 
 {
    $IPClient = Test-Connection $name -Count 1 -ErrorAction Stop
    $IPv4 = $IPClient.IPV4Address.IPAddressToString 
 } 
 catch 
 {
    $IPv4 = "Could not find $name"
 }

EDIT: Testing multiple servers

To test a list of servers, catching any that fail, one option is:

$names = "Server1","Server2","Server3"
$ipv4 = @{}

foreach($server in $names)
{
    try 
    {
        $ipClient = Test-Connection $server -Count 1 -ErrorAction Stop
        $ipv4.Add($server, $IPClient.IPV4Address.IPAddressToString)
    }
    catch 
    {
       $ipv4.Add($server, "Unreachable")
    }
 }

$ipv4 is a hashtable, which you can display like this:

$ipv4

Which gives output in a table:

Name       Value        
----       -----        
server2    Unreachable  
Server3    10.10.10.10
server1    Unreachable 

Access any item by name:

$ipv4.Server2