Values, Separated at Commas
The ConvertTo-CSV cmdlet, new with PowerShell 2.0, gives you a bit more flexibility in how you plug into CSV-formatted info.
- By Jeffery Hicks
I think it's fair to say that the comma-separated value format is an important part of any Windows administrator toolkit, especially if scripting is involved. PowerShell has always supported this format with the Import-CSV and Export-CSV cmdlets. Getting data into a CSV file relies on the latter cmdlet, but it forces you to save the information to a text file.
What if you want to use the data in the CSV format, perhaps as a PowerShell variable? Or maybe you need to use something other than a comma as the separator? PowerShell 2.0 introduces the ConvertTo-CSV cmdlet.
You use ConvertTo-CSV in the same way you might use Export-CSV. Instead of writing output to a file, it is written to the pipeline:
PS C:\> gwmi win32_logicaldisk -filter "drivetype=3" | Select DeviceID,Size,Freespace,VolumeName,SystemName | convertto-csv
Just like Export-CSV, the cmdlet includes a TYPE line; you can use -NoTypeInformation to eliminate it:
PS C:\> $d= gwmi win32_logicaldisk -filter "drivetype=3" | Select DeviceID,Size,Freespace,VolumeName,SystemName | convertto-csv -NoTypeInformation
Personally, I've not found much practical use for something like this. Although PowerShell now includes a corresponding ConvertFrom-CSV cmdlet that is the equivalent of Import-CSV:
PS C:\> ConvertFrom-CSV $d
DeviceID : C:
Size : 119926681600
Freespace : 51621105664
SystemName : GODOT7
DeviceID : F:
Size : 320070287360
Freespace : 99858821120
VolumeName : VM
SystemName : GODOT7
These are custom objects, not WMI objects, but you can work with them as you would any other object in PowerShell.
Finally, if you need a file that uses a semicolon as a delimiter -- perhaps you plan on using the file somewhere else -- this cmdlet offers the flexibility you'll need:
PS C:\> gwmi win32_logicaldisk -filter "drivetype=3" | Select DeviceID,Size,Freespace,VolumeName,SystemName | convertto-csv -NoTypeInformation -Delimiter ";" | out-file drivedata.txt
I still think the comma is king in PowerShell 2.0 and now you have a few more tools to work with data the way you want without having to parse a lot of text or jump through a lot of hoops.
Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.