Search code examples
powershellpowershell-cmdlet

Combining Powershell cmdlets issue


I've pieced together a script (sorry can't remember the source), that returns multiple attributes using two cmdlets, (Get-user & Get-mailboxstatistics). The code works as expected if I specify an individual user but when using a wildcard to return all users it only returns the attributes from Get-user, and I don't know why.

Any help in resolving this is appreciated.

    $outputCollection = @()
$users = Get-User -identity *
$mailboxes = Get-Mailboxstatistics -identity *

$users | Foreach-Object {
   #Associate objects
$userObject = $_
$mailboxObject = $mailboxes
$emailObject = $mail

#Make a combined object
$outputObject = "" | Select FirstName,Lastname,sAMAccountName,windowsemailaddress,ItemCount,Totalitemsize,TotalDeletedItemSize,DatabaseName,ServerName,LastLogonTime,LastLogoffTime
$outputObject.FirstName = $userObject.FirstName
$outputObject.Lastname = $userObject.Lastname
$outputObject.sAMAccountName = $userObject.sAMAccountName
$outputObject.windowsemailaddress = $userObject.windowsemailaddress   
$outputObject.itemcount = $mailboxObject.itemcount
$outputObject.Totalitemsize = $MailboxObject.Totalitemsize
$outputObject.TotalDeletedItemSize = $MailboxObject.TotalDeletedItemSize
$outputObject.DatabaseNAme = $mailboxObject.DatabaseName  
$outputObject.ServerName = $mailboxObject.ServerName  
$outputObject.lastlogontime = $mailboxObject.lastlogontime
$outputObject.lastlogofftime = $mailboxObject.lastlogofftime


  #Add the object to the collection
  $outputCollection += $outputObject
}

 $outputCollection

Solution

  • To help you understand I changed as little as possible. For starters I would remove the $mailboxes = Get-Mailboxstatistics -identity * line. Then, for simplicity sake, update the line below

    $mailboxObject = Get-Mailboxstatistics -identity $userObject.UserPrincipalName
    

    You need to get the statistics for the one mailbox in each loop pass. Changing how you populate the $mailboxObject should accomplish that without the need to change anything else.

    You can possibly remove $emailObject = $mail since you don't appear to be using it anywhere.

    FYI This is not tested but should work. This also assumes that the user actually has an exchange mailbox. If not there will be null values in the output.

    About efficiency

    I wanted to try and make this simpler for you to understand. However note that what Bacon Bits was trying to tell you about not running Get-Mailboxstatistics every time is true. My solution should still work though.