Nested ForEach

This topic contains 4 replies, has 3 voices, and was last updated by  js 3 months, 4 weeks ago.

  • Author
    Posts
  • #89918

    prisoner107
    Participant

    Can someone please tell me what I am doing wrong with the below code.
    Im having trouble pulling the "LastLogontime" Attribute from the Get-MailboxStatistics cmdlet, and its duplicating all the data. Im using the Invoke-All for Speed on the Get-MailboxStatics, since its usually a slow cmdlet.
    I've changed the code several times and wasted too many hours trying to make it work, i've no other choice but to ask for help.
    How can I make this an efficient script?

    $AzureUser = Get-AzureADUser -All $true | Where-Object { $_.DisplayName -match 'jose' } 
    $mb = $AzureUser  |Invoke-All {Get-MailboxStatistics -Identity $_.DisplayName}
    
      & {
        foreach ($mbx in $mb)
        {
        foreach ($Azure in $AzureUser) 
        {
                [pscustomobject] @{
                      DisplayName = $Azure.DisplayName
                      UserPrincipalName = $Azure.UserPrincipalName
                      LastDirSyncTime = $Azure.LastDirSyncTime
                      EmployeeId = $Azure.ExtensionProperty["employeeId"]
                      Licensed = if($Azure.AssignedLicenses){$TRUE}else{$False}
                      Plan = if($Azure.AssignedPlans){$TRUE}else{$False}
                      Mail = $Azure.Mail
                      AccountEnabled = $Azure.AccountEnabled
                      SamAccountName = ($Azure.DisplayName | foreach {Get-ADUser -filter  {Displayname -eq $_}}).SamAccountName
                      LastLogon = $mbx.LastLogontime
                      }
                }
            }
    }  | Export-Csv Desktop:\NewTest.csv -NoTypeInformation
  • #89921

    js
    Participant

    Can't pipe from that kind of foreach.

  • #89929

    Jon
    Participant

    I ran the code in my environment and it duplicates the data as well, honestly I have no clue why. But to get the lastlogontime I did this

    $mb = $AzureUser | % { Get-MailboxStatistics -Identity $_.displayname }
    • #89933

      js
      Participant

      How about this way...

        $mb | foreach 
        {
        $mbx = $_
        $AzureUser | foreach 
        {
          $Azure = $_
      
  • #89930

    prisoner107
    Participant

    Correct, if I drop the Invoke-All Function from the script it will work as expected. Was just trying to find a way to multithread at the same time. Might not be possible like js mentioned.

You must be logged in to reply to this topic.