none
Output Data to CSV File with headers RRS feed

  • Question

  • So I'm trying to create a powershell script that outputs a list of computers with their default printers. Here's what I have to far:

    cls

    $obj = New-Object PSObject

    $ComputerList = Import-CSV C:\test\PCList.csv

    ForEach ($Computer in $ComputerList)
        {
        $DefaultPrinter = Get-WmiObject -Query "select * from Win32_Printer where Default=True"
        $DefaultPrinterName = $DefaultPrinter.ShareName
            $obj | Add-Member WorkstationName $Computer.Name -Force
            $obj | Add-Member DefaultPrinter $DefaultPrinterName -Force
            
        Write-Output -InputObject $obj | Out-File -FilePath C:\test\PCList_defaultprinter.csv -Append
        }

    It's not formatting the CSV in a workable format. What I'd like is to have 2 columns (Workstation Name and Default Printer Name) but it's not exactly doing that.


    Any help would be greatly appreciated!!!

    Saturday, September 27, 2014 10:45 PM

All replies

  • Use Export-CSV instead of Out-File, as in:

    cls
    
    $obj = New-Object PSObject
    
    $ComputerList = Import-CSV C:\test\PCList.csv
    
    ForEach ($Computer in $ComputerList)
        {
        $DefaultPrinter = Get-WmiObject -Query "select * from Win32_Printer where Default=True"
        $DefaultPrinterName = $DefaultPrinter.ShareName
            $obj | Add-Member WorkstationName $Computer.Name -Force
            $obj | Add-Member DefaultPrinter $DefaultPrinterName -Force
            
        $obj | Export-Csv -Path C:\test\PCList_defaultprinter.csv -NoTypeInformation -Append
        }


    Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) _________________________________________________________________________________ Powershell: Learn it before it's an emergency http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx

    Saturday, September 27, 2014 11:17 PM