Search code examples
powershellloopsforeachheader

Powershell add a header on output in foreach loop


I'm sure this is very simple but I can't seem to get it. All i'm trying to do is add a header/title to the object being returned/exported so it's more readable in the end product.

What I have now:

$name | foreach {
Get-MailboxPermission $_ |? {$_.AccessRights -eq "FullAccess" -and $_.IsInherited -ne "False"} | Select User | export-csv -path $path -NoTypeInformation -Append

}

This gives me an output that looks like:

name1
name2
name3
name4
name5

However for the sake of easy reading, I want it to say the name of the mailbox it's showing the permissions for, so like this:

Mailbox 1
name1
name2
name3

Mailbox 2
name1
name2
name3

I hope that make sense, any assistance is always very appreciated.

Thanks, Lou


Solution

  • If you absolutely want a CSV you'll have to output $name to each line, resulting in

    Mailbox;User    
    $name1;$user1
    $name1;$user2
    $name2;$user1
    $name2;$user2
    

    After that you'll be able to use filters in Excel.

    You can try this

    $result = @()
    
    $record = @{
    
        "Mailbox" = ""
        "User" = ""
    
    }
    
    $name | foreach {
    $user = Get-MailboxPermission $_ |? {$_.AccessRights -eq "FullAccess" -and $_.IsInherited -ne "False"} | Select User
    
    $record.Mailbox = $_
    $record.User = $user
    $objRecord = New-Object PSObject -Property $record
    $result += $objRecord
    
    }
    
    $result | Export-Csv -Path $path -Delimiter ";" -NoTypeInformation