Powershell – Generate CSV of all locally attched printers on all PC’s in a domain

active-directorycsvpowershell

Need a little help finishing off my first Powershell scriptlet…

I would like to create a single CSV file of all the XP PC's on my AD domain (approx 3,000) and record all the printers attached. Ultimately I'd like to know how many printers we have that are locally attached.

My "Googled" together script will happily scan all the PC's using WMI for the printers and output to the screen the results. However, I can't seem to be able to refactor the code to output the results to CSV (via Export-CSV) that won't just keep overwriting the file. I want it to append to the file.

# Get the list of computer names from AD
$strCategory = "computer"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.CacheResults = -1
$objSearcher.PageSize = 5000
$objSearcher.SizeLimit = 5000

$objSearcher.Filter = ("(&(operatingSystemVersion=5*)(objectCategory=$strCategory)(operatingSystem=Windows XP*))")

$wmiPrinterClass = "win32_printer"

$colProplist = "name"
foreach ($i in $colPropList)
    {$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()
$colResults.count

# for each computer, use WMI to scan for printers
foreach ($objComputer in $colResults)
    {
    $machine = $objComputer.Properties.name
    $machine
    get-WmiObject -class $wmiPrinterClass -computername $machine | `
      ft systemName, name, shareName, Local -auto | `
      Export-CSV "c:\printers.csv"  #<<< HOW DO I STOP THIS FROM OVERWRITING???
    }

The script as it stands will scan AD for all the XP PC's and then execute a remote WMI search on Win32_Printer. How do I get all of this information into a single CSV file?

Best Answer

You want the "-noClobber" option to ExportCSV it appears.

http://ss64.com/ps/export-csv.html

I also did an alternative solution that might work:

# Get the list of computer names from AD
$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.CacheResults = -1
$objSearcher.PageSize = 5000
$objSearcher.SizeLimit = 5000
$objSearcher.PropertiesToLoad.Add("name")
$objSearcher.Filter = ("(&(operatingSystemVersion=5*)(objectCategory=computer)(operatingSystem=Windows XP*))")

$output = @()

# for each computer, use WMI to scan for printers
foreach ($objComputer in $objSearcher.FindAll())
        {
        $output += get-WmiObject -class "win32_printer" -computername $objComputer.Properties.name | ft systemName, name, shareName, Local -auto
        }

Export-CSV "c:\printers.csv" -inputObject $output
Related Topic