powershellexport-csvexchange-online

Export Exchange Online query to CSV


I'm trying to export a list of mailbox sizes of users in Exchange Online to a CSV file on the desktop of the user running the command.

The command to retrieve the information I want from Exchange Online works. So, I don't need help with that part. The only part I need assistance with is getting the results to export to a .csv on my desktop. PowerShell is running as an administrator.

Here is what I have:

# Get the current user's desktop path
$desktopPath = "$env:USERPROFILE\Desktop"

# Run the command and export the results to a CSV file
Get-EXOMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited |
    Get-EXOMailboxStatistics |
    Select-Object DisplayName, TotalItemSize, MailboxGuid |
    Sort-Object TotalItemSize -Descending |
    Export-Csv -Path "$desktopPath\MailboxStatistics.csv" -NoTypeInformation

Here is the error I'm getting:

Export-Csv : Could not find a part of the path 'C:\Users\[username]\Desktop\MailboxStatistics.csv'.
At line:5 char:5
+     Export-Csv -Path "$desktopPath\MailboxStatistics.csv" -NoTypeInfo ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Export-Csv], DirectoryNotFoundException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ExportCsvCommand

Solution

  • Your error message implies one of two causes:


    Therefore:

    # Get the current user's desktop path using the relevant .NET API.
    $desktopPath =  [Environment]::GetFolderPath('Desktop')
    
    # Run the command and export the results to a CSV file.
    # Note the use of -LiteralPath.
    Get-EXOMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited |
        Get-EXOMailboxStatistics |
        Select-Object DisplayName, TotalItemSize, MailboxGuid |
        Sort-Object TotalItemSize -Descending |
        Export-Csv -LiteralPath "$desktopPath\MailboxStatistics.csv" -NoTypeInformation