'resolve-dnsname with Try/catch and set a variable

Here is the scenario - I am running through a long list of domain names to audit them. Some of them no longer exist.

inside of my foreach loop I am doing the following among other things:

try{$nsrecords = Resolve-DnsName -name $name -Type NS}
catch{$active = 'False'}

The idea is that if the DNS Lookup fails for any reasons, Catch will catch the error and set the variable $active to 'False' that way, when the whole script runs in the end there will be a CSV output that says:

Domainname Active NameServer
test.co.nz True ns1.net.nz;ns2.net.nz
nondomian.co.nz false

however, when I run the Try/Catch with a domain I know doesn't exist anymore, the $active variable doesn't get set - I've not used try/catch before so I'm sure it's something basic that I'm missing.

Thanks



Solution 1:[1]

Maybe this will help?

    try {
            [system.net.dns]::resolve($address) | Select HostName,AddressList
        }
        catch 
        {
            $active = 'False'
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nikibon