在PowerShell中捕获错误并重写输出
我正在尝试制作一个脚本来解析一长串域名到IP地址。其中一些没有定义,我需要捕捉错误,并返回一个“空白值”。在下面的脚本中,我尝试使用基本的If/Then来做这件事,但我仍然得到一个罗嗦的错误(在底部),而不是一个空白值。任何想法如何解决这个问题?对此,我真的非常感激!在PowerShell中捕获错误并重写输出
----- ----- 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"-"
}
}
----输出/错误----
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"-"
}
}
更新的回答:
追赶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
变量(它的阵列错误/列表)...
的更多信息:
- http://vwiki.co.uk/Exceptions_and_Error_Handling_(PowerShell)
- PowerShell Tutorial – Try Catch Finally and error handling in PowerShell
- Using PowerShell $Error variable
- about_Try_Catch_Finally
更新2:
我忘了一件事 - 尝试/捕捉工作只与终止错误。 我不知道类型的错误,你的情况(因为不能复制),但有时你可能要添加到您的命令:
-Error Stop
hehe ...那么问题是什么?据我了解 - 主题是'捕捉错误在Powershell和重写输出',问题是'我需要赶上错误,只是返回一个“空白值”......所以我认为答案很简单......'使用try/chatch'。但是我已经更新了我的答案给一些例子和链接 - 我希望这可以帮到更多 –
谢谢Lukasz。读完一小段后,我意识到try/catch是多么简单,编辑原始问题,再次感谢! –
这是奇怪的。我不能重现调用'[System.Net.Dns] :: GetHostAddresses(“doesnotexit”)[0] .IPAddressToString;'你使用的是什么版本的powershell? –
嗨尼克 - 我正在使用版本5.我跑了上面,并再次得到错误... –
甚至陌生人!我也在版本5中。嗯... –