Powershell export-csv ... how to include null or error condition for any object that failed?

Hello,

I have spreadsheet of computers I'm looking to get information on.  I'm running a powershell command against that list of computers, exporting to a CSV, which is working fine.  

However, in the exported CSV, any computers that the command returned an error on are skipped in the CSV.  
I'm looking to include the error condition (ie. "Cannot find an object with identity <computername>") for these in the exported CSV, or even simply a blank row with just the computer name (so I can see which computers the command skipped/failed on).

For example, instead of getting only the following in the CSV (skipping Computer2 which could not be found)...

Computer1        True
Computer3        True
Computer4        True

... I'm looking for something like this:

Computer1        True
Computer2        "error condition" or <blank row>
Computer3        True
Computer4        True

Here's the powershell command I'm running:

$computers = Import-CSV list.csv
$computers | foreach-object {Get-ADComputer -Identity ($_.Servername) -Properties IPv4Address,OperatingSystem,LastLogonTimeStamp,CreateTimeStamp,CanonicalName | select-object Name,IPv4Address,OperatingSystem,@{Name="Lastlogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}},CreateTimeStamp,CanonicalName} | Export-csv servers.csv -notypeinformation

Open in new window


Note: Googling how to achieve this, the closest I saw was https://stackoverflow.com/questions/29550324/how-can-i-output-all-the-output-of-a-called-command-in-powershell-script ... but that appeared more complex that I'm looking for.
LVL 1
JAMAsked:
Who is Participating?
 
oBdACommented:
Try it like this:
Import-Csv list.csv |
	ForEach-Object {
		$ComputerName = $_.Servername
		Try {
			Get-ADComputer -Identity $ComputerName -Properties IPv4Address, OperatingSystem, LastLogonTimeStamp, CreateTimeStamp, CanonicalName -ErrorAction Stop |
				Select-Object -Property *, @{Name='Lastlogon'; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}
		} Catch {
			$_.Exception.Message | Select-Object -Property @{n='Name'; e={$ComputerName}}, @{n='Error'; e={$_}}
		}
	} |
	Select-Object -Property  Name, IPv4Address, OperatingSystem, Lastlogon, CreateTimeStamp, CanonicalName, Error |
	Export-Csv servers.csv -NoTypeInformation

Open in new window

2
 
JAMAuthor Commented:
oBdA,

Works and exactly what I was looking for , thank you so much!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.