Search code examples
powershellfor-loopforeachexchange-server-2010

Output Powershell results to individual text documents


I figured this might be an easy answer, but for the life of me I can't suss out why this simple thing seems to be beating me. I am looking to output the results of

Get-Mailbox –Server MYserverName | Get-MailboxPermission | FL

piped into individual text files for each individual mailbox, with the text file named for the mailbox - e.g. I want to have a folder with the content:

  • C:\Example\MailboxUser1.txt
  • C:\Example\MailboxUser2.txt
  • C:\Example\MailboxUser3.txt

with each containing the mailbox permission results.

I know I can do a foreach loop along the lines of:

ForEach-Object {Out-file $_.name}

to generate the output files, but I'm not too sure how I would do this in a single step to get the permissions for all my mailboxes into individual files (I know this will give me a lot of text files!)?


Solution

  • Something along the lines of:

    $directory = "C:\example\"
    $count = 0
    
    Get-Mailbox –Server "MYserverName" | Foreach-Object {
        Get-MailboxPermission | Format-List |
            Out-File (Join-Path $directory "MailboxUser-$(++$count).txt")
    }
    

    At each pass of the ForEach-Object loop (mailbox), a file will be generated with the output of the Get-MailboxPermission command.

    ++$count increments the value just before using it (as opposed to $count++)

    If you prefer to user the Name property of the mailbox object to name the files:

    $directory = "C:\example\"
    
    Get-Mailbox –Server "MYserverName" | Foreach-Object {
        $mailboxName = $_.Name
        Get-MailboxPermission | Format-List |
            Out-File (Join-Path $directory "MailboxUser-$mailboxName.txt")
    }