如何将PowerShell脚本Catch报错与对应IP写入InfoBlox查询CSV
修正PowerShell脚本:将IP关联网络未找到错误写入CSV
原脚本用于遍历IP地址集合检查InfoBlox中的DNS条目,但捕获到“A network was not found for this address”错误时,无法将错误信息与对应IP关联写入CSV。以下是修改后的脚本,实现错误信息与IP的关联记录:
Set-IBConfig -ProfileName 'MyGrid' -WAPIHost dns.xx.xxx -WAPIVersion latest -Credential (Get-Credential) -SkipCertificateCheck $resultsFolder = "C:\Users\x\Documents\20220920" $AviClusterList = 'C:\Users\x\Documents\20220920\AviCluster.csv' $outputCsvPath = "$resultsFolder\AviVirtualIPReservations.csv" # 如需覆盖旧输出文件,取消注释下面一行 # if (Test-Path $outputCsvPath) { Remove-Item $outputCsvPath -Force } $AviClusters = Import-Csv $AviClusterList foreach ($AviCluster in $AviClusters) { $AviClusterName = $AviCluster.FQDN $SEVirtualIPs = Import-Csv "$resultsFolder\$AviClusterName.csv" foreach($SEVirtualIP in $SEVirtualIPs){ $currentIp = $SEVirtualIP.'Service Engine Virtual IPs' try { $ipObj = Get-IBObject -type ipv4address -filters 'status=USED',"ip_address=$currentIp" -ErrorAction Stop # 生成查询成功的记录对象 [PSCustomObject]@{ 'ip_address' = $currentIp 'Infoblox Reservation Name' = $ipObj.names -join ', ' 'Status' = $ipObj.status 'In Conflict' = $ipObj.is_conflict 'Error Message' = $null } | Export-Csv -Path $outputCsvPath -Append -NoTypeInformation -Force } catch { # 判断是否为目标错误信息 if ($_.Exception.Message -match "A network was not found for this address") { $errorMsg = "A network was not found for this address" } else { $errorMsg = $_.Exception.Message } # 生成错误关联记录对象 [PSCustomObject]@{ 'ip_address' = $currentIp 'Infoblox Reservation Name' = $null 'Status' = $null 'In Conflict' = $null 'Error Message' = $errorMsg } | Export-Csv -Path $outputCsvPath -Append -NoTypeInformation -Force } } }
关键改动说明:
- 新增
Error Message列,专门记录IP对应的错误信息 - 提取当前处理的IP到
$currentIp变量,确保错误发生时能精准关联到具体IP - 统一用自定义对象输出结果,无论查询成功还是失败,对象结构保持一致,避免CSV列混乱
- 添加
-ErrorAction Stop参数,确保Get-IBObject的错误能被catch块捕获 - 保留对其他未知错误的记录,便于排查非预期问题
内容的提问来源于stack exchange,提问作者asthmatic_weasel
相关产品推荐
相关产品推荐

