在PowerShell中尝试/捕获Add-DnsServerResourceRecordA

时间:2016-07-19 12:24:56

标签: powershell exception try-catch

我希望捕获在PowerShell中使用Add-DnsServerResourceRecordA添加带有-CreatePTR的DNS记录时发生的异常,但不存在反向查找区域。
但没有错误。如果我挑起错误,会弹出一个简单的菜单并通知我情况。但独立于-ErrorAction开关,$error变量不会收到错误。我的错是什么?

感谢您的回复。

PS C:\Users\xyz>> Add-DnsServerResourceRecordA -Name "test-mwi4" -IPv4Address 1.1.1.1 -CreatePtr -ZoneName contoso.biz -ErrorAction Continue Add-DnsServerResourceRecordA : Failed to create PTR record. Resource record test-mwi4 in zone mn-man.biz on server MNDEMUCDC010 is created successfully, but corresponding PTR record could not be created. At line:1 char:1 + Add-DnsServerResourceRecordA -Name "test-mwi4" -IPv4Address 1.1.1.1 -CreatePtr - ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (test-mwi4:root/Microsoft/...ResourceRecordA) [Add-DnsServerResourceRecordA], CimException + FullyQualifiedErrorId : WIN32 9715,Add-DnsServerResourceRecordA

谢谢!

1 个答案:

答案 0 :(得分:0)

为了在try catch块中使用此命令,请使用以下代码:

Try
{
    Add-DnsServerResourceRecordA -Name "test-mwi4" -IPv4Address 1.1.1.1 -CreatePtr -ZoneName contoso.biz -ErrorAction Stop
}
Catch
{
    Write-Host "Error while adding pointer record:`n$($Error[0].Exception.Message)"
}

$Error[0]返回:

$Error[0]
Add-DnsServerResourceRecordA : Failed to get the zone information for 
contoso.biz on server HYDLPT487.
At line:3 char:5
+     Add-DnsServerResourceRecordA -Name "test-mwi4" -IPv4Address 1.1.1 ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (test-mwi4:root/Microsoft/...Resou 
   rceRecordA) [Add-DnsServerResourceRecordA], CimException
    + FullyQualifiedErrorId : WIN32 1722,Add-DnsServerResourceRecordA