Out-File is writing different rows

by deiandrei at 2012-11-16 00:55:20

Hi guys,

I am getting started with Powershell. I have only little experience in scripting, so I got stuck in a simple script.
Here is the script:
Get-WmiObject win32_printer | ForEach-Object {$.caption,$.comment,$.default,$.deviceid,$.drivername,$.location,$.name,$.portname,$.sharename}|Out-File D:\Printerlist.csv

This script is writing some printer information to a .csv file. But the problem is that every attribute is written in a separate row.
At the moment, the output looks like this:
caption1
comment1

sharename1
caption2
comment2

sharename2

I would like to have the information for every printer in one row and for the next printer in the next row. Like:
caption1,comment1,default1,…,sharename1
caption2,comment2,default2,…,sharename2

Thank you in advance!
by MattG at 2012-11-16 03:23:35
Hi,

There are a few ways to accomplish this. My recommendation would be to work with the Export-Csv cmdlet. Export-Csv requires an object to passed into it so you will either need to pass in the entire object returned by “Get-WmiObject win32_printer” or create a custom object with just the fields you want. Here’s what I did:
Get-WmiObject win32_printer |
ForEach-Object { New-Object PSObject -Property @{Caption=$
.caption; Comment=$.comment; Default=$.default; DeviceId=$.deviceid; DriverName=$.drivername; Location=$.location; Name=$.name; PortName=$.portname; Sharename=$.sharename} } |
Export-Csv Proceses.csv -NoTypeInformation
by deiandrei at 2012-11-16 06:10:38
Thank you, this is what I needed.
But in the output file, the caption is written normally, while all others are written in quotes. Any idea why?
I can easily edit the list in Excel, that is no problem, but still…is it normal that all attributes but one appear in quotes?
by MattG at 2012-11-16 09:24:48
Sorry. I couldn’t tell you. When I run it, I don’t get quotes in any fields when I open the csv from Excel 2010.
by ArtB0514 at 2012-11-16 09:50:14
When PowerShell generates a csv file, it inserts double quotes for any element that might contain a space or a delimiter character which are all visible when the file is opened in a text editor like Notepad. Excel strips the double quotes when it imports the file. Try this experiment: Open your csv file in Excel and then resave it (use a different name!) also in csv. Compare the file sizes. You should see that the Excel generated csv file is smaller.
by Makovec at 2012-11-18 07:48:47
Oh, my answer was lost :frowning: So once again.

Honestly, I don’t like the idea of ForEach-Object in this case (it’s not necessary here). You can simply use Select-Object to filter properties you want to pass down the pipeline:
Get-WmiObject Win32_Printer | Select-Object caption, comment, default, deviceid, drivename, location, name,portname, sharename | Export-Csv -Path D:\printerlist.csv -NoTypeInformationThe code is much cleaner then.

David