Author Posts

October 9, 2017 at 9:03 am


I have a script which uses a scriptblock to retrieve certificate information from various servers in our environment.
Some of these servers are unreachable or the information is unobtainable for various reasons and an error is generated as expected and the script will then move on to the next server in the list.

All information returned successfully is recorded and a .CSV file is created.

I would like to also store the error message in the .CSV file to investigate the problematic machines and determine the issue of these.

Can anyone help me to find out how to also send these error messages to my .CSV file?

Many thanks in advance.

October 9, 2017 at 9:46 am

Catch the error message and append to the CSV, using the Add-Content cmdlet.

October 9, 2017 at 10:41 am

Many thanks for your reply postanote.
I guess reading back through my initial post I can see why you replied with the suggestion you did.

My script basically writes the returned values from a scriptblock against a list of servers to a variable which is exported to CSV once the list is complete.

However, I also want the error object information also entered into my list of returned objects if possible?
It was actually the process of how I do this that I would like to know as I have no experience or great understanding of error handling.

Many thanks.

October 9, 2017 at 2:29 pm

You might look at adding the -ErrorVariable parameter to the cmdlet that might generate the error. If the variable you defined to capture errors has a value, write that into your csv instead of a row of valid data. Does that help?

October 10, 2017 at 8:40 pm

If I am understanding your problem correctly, then the way I would go about it is to assemble psobjects for each server (including the properties you want) and then output the collection to a csv at the end. That way, you can output an object for all servers, and include the error when it throws an error. The following example pings each server.

$Computers = Get-Content -Path C:\path\to\computers.txt
$Output = @()
Foreach ($Computer in $Computers) {
    try {
        Test-Connection -ComputerName $Computer -Count 1  -ErrorAction Stop | Out-Null
        $Properties = @{
            Computer = $Computer
            Results  = "Success"
        $obj = New-Object -TypeName PSObject -Property $Properties
        $Output = $Output + $obj
    catch {
        $Properties = @{
            Computer = $Computer
            Results  = $_.Exception
        $obj = New-Object -TypeName PSObject -Property $Properties
        $Output = $Output + $obj
$Output | Export-CSV -Path C:\path\to\output.csv

Hope this helps.

October 12, 2017 at 12:17 am

Try/Catch blocks are the way to go. Ian has a good example below.