$csv = Get-Content c:\users\user\downloads\OutofContact.csv
foreach ($computer in $csv)
{
try{
$report = New-Object -TypeName PSObject -Property @{
ComputerName = (Resolve-DnsName $computer).Name
IPAddress = (Resolve-DnsName $computer).IPAddress
}
$report | select-object -Property ComputerName, IPAddress | Export-Csv -Path Results.csv -notype -append
}catch{
Write-Error "$computer not found" | Export-Csv -Path Results.csv -notype -append
}
}
我正在使用上面的代码来检查DNS条目以获取计算机列表。 DNS中不存在某些计算机,并且将引发错误。我希望这些机器将错误写入CSV,但是它们只是显示为空白行。
如何获取也要写入CSV的错误?
答案 0 :(得分:1)
我将重构和优化重复的调用,只在最后添加一个对象...
类似这样的东西:
#$csv = Get-Content c:\users\user\downloads\OutofContact.csv
# test
$csv = @('localhost', 'doesnotexist', 'localhost', 'doesnotexist')
$allReports = [System.Collections.ArrayList]::new()
foreach ($computer in $csv)
{
$report = [pscustomobject]@{
'ComputerName' = $computer
'IPAddress' = 'none'
'Status' = 'none'
}
try
{
# this can return multiple entries/ipaddresses
$dns = Resolve-DnsName $computer -ErrorAction Stop | Select -First 1
$report.ComputerName = $dns.Name
$report.IPAddress = $dns.IPAddress
$report.Status = 'ok'
}
catch
{
Write-Error "$computer not found"
}
finally
{
$null = $allReports.Add($report);
}
}
# write to csv file once...
$allReports | Export-Csv -Path c:\temp\Results.csv -NoTypeInformation #??? keep this? -Append
您将需要遍历代码并调试并更改为特定要求。