Lightman
Lightman

Reputation: 1

Splitting arrays in foreach

I'm using Exchange message tracking to split recipients from an array so they appear on their own line.

When I run the following:

foreach ($recepient in $recepients){
    $recepient.Recipients
}

The recipients are shown as a list.

However, when I add the variable as an expression, the output show's the recipients still in the array.

Also tried using:

Split-Array -inArray $user -Size 1

without much progress.

The output is not splitting the recipient array. Example:

Timestamp           recipients       Messagesubject      eventID
---------           ----------       ----------------    -------
01/01/2019 10:11:00 {User1,User2}    Subject             Deliver
$Report = @()

$Sender = "[email protected]"
$recepients = Get-MessageTrackingLog -EventId "Deliver" -Sender $Sender -Start (Get-Date).AddDays(-8) -MessageSubject "Subject"

foreach ($recepient in $recepients) {
    $user = $recepient.Recipients

    $Data = $recepient | select timestamp,@{L=”recepients”;E={$user}},eventid

    $report += $Data
}
$Report

The goal is to have each user on their own line

Timestamp           recipients     Messagesubject      eventID
---------           ----------     ----------------    -------
01/01/2019 10:11:00 User1          Subject             Deliver
01/01/2019 10:11:00 User2          Subject             Deliver

Upvotes: 0

Views: 264

Answers (2)

Lightman
Lightman

Reputation: 1

Brilliant thank you. Expended using pscustomobject as well as adding this to a variable.

Using nested foreach loop made more sense.

Upvotes: 0

Olaf
Olaf

Reputation: 5232

If you have nested arrays in a result and you want to extract them you can use a nested loop and a custom object like this:

foreach ($recepient in $recepients){
    Foreach ($SingleRecipient in $recepient.Recipients) {
        [PSCustomObject]@{
            User = $SingleRecipient
            timestamp = $recepient.timestamp
            MessageSubject = $recepient.MessageSubject
            eventid = $recepient.eventid
        }
    }
}

Upvotes: 2

Related Questions