• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2936
  • Last Modified:

Sort CSV by Column Name in Powershell

I'm using the below script, however would like the results sorted Ascending by Mailbox name.  Where do I put the Sort command in the script for this? I tried putting Sort-Object Mailbox at the end, but it did not work.  Thanks in advance.

$Mailboxes = Get-Mailbox -Filter {RecipientTypeDetails -eq "UserMailbox"} -ResultSize Unlimited
$Output = @()
ForEach ($Mailbox in $Mailboxes) {
 $Calendar = (($Mailbox.PrimarySmtpAddress.ToString())+ ":\" + (Get-MailboxFolderStatistics -Identity $Mailbox.DistinguishedName -FolderScope Calendar | Select-Object -First 1).Name)
 $Permissions = Get-MailboxFolderPermission -Identity $Calendar
 ForEach ($Permission in $Permissions) {
  $Permission | Add-Member -MemberType NoteProperty -Name "Mailbox" -value $Mailbox.DisplayName
  $Output = $Output + $Permission
$Output | Select-Object Mailbox, User, {$_.AccessRights}, IsValid | Export-Csv -Path C:\CalendarPermissions.csv -NoTypeInformation | Sort-Object Mailbox

Open in new window

2 Solutions
imkotteesSenior Messaging EngineerCommented:

always sort should come before selecting/formatting the output.

Try like this.

$Output | Sort-Object Mailbox | Select-Object Mailbox, User, {$_.AccessRights}, IsValid | Export-Csv -Path C:\CalendarPermissions.csv -NoTypeInformation

I would typically put it after the Select-Object command, but it will work in front of it as well.  This can be important when you are using Select-Object to create calculated properties, and you then want to sort by that calculated property.  But yes, it has to come before formatting commands.

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now