Powershell: Exporting a CSV of Computer Data

I had an urgent request to pump out some data regarding a list of computer accounts similar to this:


CompA
CompB
CompC

I thought “No problem, a quick ‘Get-ADComputer’ piped to ‘Export-CSV’ and we’re golden.  Except for the fact that Export-CSV doesn’t handle appends.

So, there’s a different way to do it – create your own custom objects.

Code appears below.

import-module ActiveDirectory

$comps = Get-content "C:\system\CompData\comps.txt"
$outfile = "c:\system\compdata\results.txt"
$Computers = @()

foreach ($comp in $comps)
{
 $temp = Get-ADComputer $comp -Properties CanonicalName,Description,DNSHostName,LastLogonDate,DistinguishedName,Name,ObjectClass,ObjectGUID,SamAccountName,SID

 $compobject = New-Object System.Object
 $compobject | Add-Member -type NoteProperty -name CanonicalName -value $temp.CanonicalName
 $compobject | Add-Member -type NoteProperty -name Description -value $temp.Description
 $compobject | Add-Member -type NoteProperty -name DNSHostName -value $temp.DNSHostName
 $compobject | Add-Member -type NoteProperty -name LastLogonDate -value $temp.LastLogonDate
 $compobject | Add-Member -type NoteProperty -name DistinguishedName -value $temp.DistinguishedName
 $compobject | Add-Member -type NoteProperty -name Name -value $temp.Name
 $compobject | Add-Member -type NoteProperty -name ObjectClass -value $temp.ObjectClass
 $compobject | Add-Member -type NoteProperty -name ObjectGUID -value $temp.ObjectGUID
 $compobject | Add-Member -type NoteProperty -name SamAccountName -value $temp.SamAccountName
 $compobject | Add-Member -type NoteProperty -name SID -value $temp.SID

 $Computers += $compobject
}

$Computers | export-csv -Path $outfile
Advertisement
This entry was posted in Powershell and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s