r/PowerShell • u/SysAdminEnby • Jun 07 '24
Question Export CSV and have resulting CSV have different headers than what's called
I'm exporting a file from Microsoft.Graph with specific user details. I'm wondering if its possible to change the headers in the resulting CSV without having to export the file first then import it and modify it. I also need to add some columns that will have a header but the script will not be searching for the fields.
6
u/blooping_blooper Jun 07 '24
just pipe the data through a foreach and convert them to pscustomobject with your desired properties, then export to csv
e.g.
$data | % { [pscustomobject]@{
col1=$_.col1
col2=(get-date).ToString("D")
col3=$_.col2
} | Export-Csv -path c:\temp\data.csv -notypeinformation }4
u/alt-160 Jun 07 '24
Just putting it in as a maybe, because i see it so often...
If you are using the CSV as some sort of transportable data type there's possibly a better option. What i mean is that if you're intent for CSV is to then use it as an input for another step, there's a better path.
If you're not aware (and many are not), powershell has provided a pair of commands that are my favorite for this:
* Export-CliXml
* Import-CliXml
The value of these commands is that the export command exports the object(s) out to a fully structured xml file. This file records the properties, their data types, and the property hierarchy (which csv can never do). Property hierarchy is cases like: $someObject.SomeProperty.SomeOtherProperty.SomeLastProperty.
Import-CliXml returns that data back to powershell in the exact same way it was before export.
So, for example...
$listOfObjects = Get-SomeListOfObjects -SomeParameter "some value here"
$listOfObjects | Export-CliXml c:\some\path\and-file.xml
$listOfObjects2 = Import-CliXml c:\some\path\and-file.xml
In the above, $listOfObjects2 is has the same stuff as $listOfObjects. The value of this is the preservation of data types ( have you had to deal with formatting dates out to csv? or some data that has commas in it!).
This is especially handy for collecting data from one connection to be used in another in an different powershell window. It's also a very easy and complete way to store a backup of objects.
Now, suppose you don't want ALL the properties of each object to be saved out. Fine! Use Select-Object in between:
$listOfObject | Select name, id, modified, otherProp, thisProp | Export-CliXml c:\path\file.xml
The select in between causes only those props to go out just like what would be in the returned set if you stored it in a variable.
1
u/ollivierre Jun 08 '24
Adding to this export to JSON instead of XML when working with web technologies. XML is good for on prem stuff.
1
12
u/meon_be Jun 07 '24
Generic solution, this is not specific to MSGraph:
You can shorten "label" to jus "l" and expression to just "e", so