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

I'm using the above code to check the DNS entries for a list of machines. Some of the machines do not exist in DNS and will throw an error. I want those machines to write the error into the CSV, however they just show up as blank rows.

How can I get the errors to write to the CSV as well?

1 Answer 1

1

I would refactor and optimize duplicate calls, and only add one object at the end...

Something like this:

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

You will want to walk through the code and debug and change to your specific requirements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.