Pickle
Pickle

Reputation: 1124

Writing errors to CSV in Powershell

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

Upvotes: 0

Views: 3569

Answers (1)

Kory Gill
Kory Gill

Reputation: 7153

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.

Upvotes: 1

Related Questions