PowerShell tutorial – Write a CSV file with PowerShell using the Export-CSV

.

“What consumes your mind controls your life.”

Hello Everyone,

Hope you all are doing well.

In this article, we are going to look at how to use the Export-CSV CMDLET, how to prevent common mistakes, and what different options there that we can use.

We have good list of articles on PowerShell, please have a look.

https://knowledge-junction.in/category/technology-articles/powershell-cmdlets/

So without getting late, let’s get started.

Background

  • With PowerShell, we can extract all kinds of information from services like Active Directory or Microsoft 365.
  • But sometimes we need to process this information further in Excel or another system.
  • To do this we can use the Export-CSV function in PowerShell.
  • The Export-CSV function converts PowerShell objects into a CSV string and saves them into a CSV file.
  • If we only need a CSV string, then we can also use the ConvertTo-CSV CMDLET in PowerShell.

Details

  • Open PowerShell ISE.
  • Now ran the PowerShell with the following cmdlet.

Prerequisites

  • Install PowerShell ISE / PowerShell / Visual Studio Code if its not installed.

Export-CSV

The Export-CSV cmdlet is very simple and only has a few properties that are useful:

  • Path – (Required) Location of the CSV file
  • NoTypeInformation – Removes the type information header from the output. Not needed any more in PowerShell 6
  • Delimiter – Default is comma, but we can change it
  • Append – Append to an existing CSV file
  • Force – Useful in combination with Append
  • NoClobber – Don’t overwrite existing files
  • UseQuotes – (PowerShell 7 only) wrap values in quotes or not

We are going to start with something simple, exporting our Microsoft 365 users to a CSV file. We are going to use Azure AD throughout the examples here, make sure connect the Azure AD first.

Connect-AzureAD

The Get-AzureADUser cmdlet returns all the users in our Microsoft 365 tenant, as we can see in the screenshot below. What we are going to do is to export this output to a CSV file. To do this we can simply pipe the Export-CSV cmdlet behind it:

Get-AzureADUser

Microsoft 365: PowerShell cmdlet - Output1
fig: Microsoft 365: PowerShell cmdlet – Output1

Get-AzureADUser | Export-Csv E:\PowerShellScripts\azureadusers.csv -NoTypeInformation

Sounds easy, right? Well, if we open the CSV file, we will notice that we got a bit more than we needed and not the nice list that we had seen in PowerShell before.

Microsoft 365: Export-CSV - Output1
fig: Microsoft 365: Export-CSV – Output1

So why is this happening? The Export-CSV cmdlet exports all the individual objects from the Get-AzureADUser cmdlet. If we look up a single Azure AD user, then we can see all the data that is returned from a single user object:

Get-AzureADUser -Filter "Displayname eq 'Khasim Shaik'" | select *

Microsoft 365: PowerShell cmdlet - Output2
fig: Microsoft 365: PowerShell cmdlet – Output2

How to Export the correct information with Export-CSV

What we need to do is first select the correct information (properties) that we need before we export the user objects to a CSV file.

Get-AzureADUser | select userprincipalname, displayname, jobtitle, department, city | Export-CSV E:\PowerShellScripts\azureadusers.csv -NoTypeInformation

This will return the selected fields from each user in a nice CSV file that we can use:

Microsoft 365: Export-CSV - Output2
fig: Microsoft 365: Export-CSV – Output2

Appending to CSV file with PowerShell

On some occasions, we may want to append information to a CSV file with PowerShell. Let’s say we want to add the manager of each user to the list. There is a more efficient way to do this, but in this case, we are going to loop through all the users and get the manager from Azure AD.

For this example, we create a custom PowerShell object that will hold the user information and the manager. With the -append switch we can add the user to the CSV file.

$users = Get-AzureADUser 
$users | ForEach-Object { 
$Manager = Get-AzureADUserManager -ObjectId $_.ObjectId 
$user =[pscustomobject]@{ 
'Displayname' = $_.Displayname 
'JobTitle' = $_.JobTitle 
'Department' = $_.Department 
'Manager' = $Manager.Displayname}
$user | Export-CSV E:\PowerShellScripts\azureadusers.csv -Append -NoTypeInformation -Force} 

We have added the -Force switch as well. This way the CSV file will be created if it doesn’t exist and objects that have mismatched properties can still be written to the CSV file. It will only write the properties that match though, other properties are discarded.

Microsoft 365: Export-CSV - Output3
fig: Microsoft 365: Export-CSV – Output3

Other useful Export-CSV parameters in PowerShell

There are a couple of other parameters that are useful when we are using the Export-CSV cmdlet in PowerShell.

NoClobber

By default, the Export-CSV cmdlet will overwrite any existing file when used. If we don’t want this, then we can add the –NoClobber parameter. This way, if the file already exists, we will get an error, preventing us from overwriting the file.

Get-AzureADUser | select userprincipalname, displayname, jobtitle, department, city | Export-CSV E:\PowerShellScripts\azureadusers.csv -NoTypeInformation -NoClobber

Microsoft 365: PowerShell cmdlet - Output3
fig: Microsoft 365: PowerShell cmdlet – Output3

Delimiter

The values in a Comma Separated Values File (CSV) are by default separated with a comma. Not all applications follow this standard. So when we need to import the data into another application that required a semicolon ( ; ) for example, then we can change the delimiter.

Make sure that we enclose the new delimiter in quotation marks:

Get-AzureADUser | Select-Object -Property userprincipalname, displayname, jobtitle, department, city | Export-CSV E:\PowerShellScripts\azureadusers.csv -NoTypeInformation -Delimiter ';'

Microsoft 365: Export-CSV - Output4
fig: Microsoft 365: Export-CSV – Output4

UseQuotes

When we export objects in PowerShell 5 or 6 then all values are wrapped in quotation marks. On some occasions, we might don’t want that. If we are using PowerShell 7 then we can use the -UseQuotes parameter.

This parameter has a couple of options:

  • AsNeeded
  • Always (default)
  • Never

Get-Process | export-csv -Path E:\PowerShellScripts\azureadusers.csv -UseQuotes AsNeeded

Wrapping Up

The Export-CSV cmdlet is a PowerShell function that we use quite a lot. It’s useful to pull data out of Microsoft 365 quickly for reports or other tasks. Make sure we select first the correct properties when exporting objects. This is the most made mistake when it comes to exporting PowerShell data to Excel.

.

Hope this article will help us how to write a CSV file with PowerShell using the Export-CSV function.

Also get my article updates on my social media handles.

LinkedIn – https://www.linkedin.com/in/khasim-shaik-8784a1232/

Twitter – https://twitter.com/KhasimShaik2009

Facebook – https://www.facebook.com/profile.php?id=100078255554660

Thank you for your support, will catch up with new article soon.

Keep learning and keep smiling.

Thanks.

Khasim Shaik

SharePoint & Power Platform Developer at OS InfoTech

You may also like...

3 Responses

  1. January 20, 2023

    […] Export-Csv – Write a CSV file with PowerShell using the Export-CSV – https://knowledge-junction.in/2022/10/31/write-a-csv-file-with-powershell-using-the-export-csv-func… […]

  2. April 10, 2023

    […] We already have very good article for writing objects / arrays to CSV file, please have a look – Write a CSV file with PowerShell using the Export-CSV […]

  3. October 8, 2023

    […] We have detailed article on exporting data to CSV file. Kindly please have a look – PowerShell tutorial – Write a CSV file with PowerShell using the Export-CSV […]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Microsoft 365

Subscribe now to keep reading and get access to the full archive.

Continue reading