Sort csv out put file in desending by Mailbox size with PowerShell

315 Views Asked by At

i have a script which is working without any problem, my only issue is that i can't order the output as i needed.

I've tried to remove the Sort-object CmdLet but it didn't change any thing, also I've tried to "play" with diffrient of variation of the Sort-object CmdLet.

here is the code:

  $users = Import-Csv "C:\CSV Test\Alias_test.csv"

  foreach ($user in $users) {

  Get-MailboxStatistics -Identity $user.UserName |

   Select-Object @{l="User Name";e="DisplayName"},

   @{l="Mail Box Size";e="TotalItemSize"}, 

   @{l="TotalEmails?";e="itemcount"} |

   Sort-Object -Property ItemCount|

   Export-Csv "C:\CSV Test\Mailboxe_size.csv" -Append -NoTypeInformation

                             } #end of ForEach loop

The csv file looks like that:

Wrong order

Thanks alot for your help

1

There are 1 best solutions below

7
On

There are two problems with your current script.

First is that each users mailbox statistics are sorted individually, so move the Sort-Object statement outside of the loop.

Second problem is that by the time you sort the objects, the ItemCount property no longer exists, since you've renamed it to TotalEmails?, so make sure you update the Property argument:

$users = Import-Csv "C:\CSV Test\Alias_test.csv"

$stats = foreach ($user in $users) {
    Get-MailboxStatistics -Identity $user.UserName |
    Select-Object @{l="User Name";e="DisplayName"},
    @{l="Mail Box Size";e="TotalItemSize"}, 
    @{l="TotalEmails?";e="itemcount"} 
} #end of ForEach loop

$Stats |Sort-Object -Property TotalEmails? |Export-Csv "C:\CSV Test\Mailboxe_size.csv" -Append -NoTypeInformation