Dominic Brunetti
Dominic Brunetti

Reputation: 1069

Catching error in Powershell and rewriting output

I'm trying to craft a script to resolve a long list of domain names to IP addresses. Some of these aren't defined and I need to catch the error and just return a "blank value." In the script below, I tried doing this using a basic If/Then, but I still get a wordy error (at the bottom) rather than just a blank value. Any ideas how to get around this? I really appreciate it!

----- SCRIPT -----

$names = Get-Content C:\temp\names.txt
ForEach ($name in $names) {
$ipAddress = [System.Net.Dns]::GetHostAddresses("$name")[0].IPAddressToString;
if ($ipAddress) {
    Write-Host $name"-"$ipAddress 
    }
else {
    Write-Host $name"-"
     }
}

---- OUTPUT/ERROR ----

mydomain.com-1.2.3.4
yourdomain.com-4.3.2.1
Exception calling "GetHostAddresses" with "1" argument(s): "The requested name is valid, but no data of the requested type was found"
anotherdomain.com-5.5.5.5

---- What I'd Like to See -----

mydomain.com-1.2.3.4
yourdomain.com-4.3.2.1
NOTDEFINEDDOMAIN.tld-
anotherdomain.com-5.5.5.5

---- HERE'S THE SOLUTION THAT WORKED - THANK YOU!----

$names = Get-Content C:\temp\names.txt

ForEach ($name in $names) {
Try {
    $ipAddress = [System.Net.Dns]::GetHostAddresses("$name")[0].IPAddressToString;
    Write-Host $name"-"$ipAddress
    }
Catch {
    Write-Host $name"-"
    }
}

Upvotes: 2

Views: 2140

Answers (1)

Lukasz Mk
Lukasz Mk

Reputation: 7350

Update of answer:

Catching error in Powershell and rewriting output

I need to catch the error and just return a "blank value

Use try/catch:

$names = Get-Content C:\temp\names.txt
ForEach ($name in $names)
{
   try
   {
      $ipAddress = [System.Net.Dns]::GetHostAddresses("$name")[0].IPAddressToString;
      Write-Host $name"-"$ipAddress 
   }
   catch
   {
       Write-Host $name"-"
       $_.Exception.Message   # <- Check this to read and rewrite exception message
   }
}


---- What I'd Like to See -----

If you want - you can manipulate of exception message like as string - this is line to get message in catch block:

$_.Exception.Message


Other way to get info about errors is $Error variable (it's the array/list of errors)...


More information:


Update 2:

I forgot about one thing - try/catch working only with terminating errors. I'm not sure about type of error in your case (because can't reproduce it), however sometimes you may want to add to your command:

-Error Stop

Upvotes: 2

Related Questions