在Powershell中捕获错误并重写输出

时间:2016-06-07 18:09:40

标签: powershell

我正在尝试制作一个脚本来解析一长串域名到IP地址。其中一些没有定义,我需要捕获错误,只返回一个空白值。"在下面的脚本中,我尝试使用基本的If / Then,但我仍然得到一个罗嗦的错误(在底部),而不仅仅是一个空白值。任何想法如何解决这个问题?我真的很感激!

----- 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

----我想看到的内容-----

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

----在这里工作的解决方案 - 谢谢!----

$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"-"
    }
}

1 个答案:

答案 0 :(得分:2)

回复更新:

  

在Powershell中捕获错误并重写输出

     

我需要捕获错误并返回“空值

使用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
   }
}


  

----我想看到什么-----

如果你想 - 你可以像字符串那样操纵异常消息 - 这是在catch块中获取消息的行:

$_.Exception.Message


获取错误信息的其他方法是$Error变量(它是数组/错误列表)......


更多信息:


更新2:

我忘记了一件事 - 尝试/捕获仅用于终止错误。 我不确定你的情况下的错误类型(因为无法重现它),但有时你可能想要添加到你的命令:

-Error Stop