#############################################################################
#
# This script runs Get-MailboxFolderPermission for a valid mailbox specified
# by the user.  It displays the folder-level permissions on screen and also
# dumps them to a text file.
#
# Created by jtedoff@microsoft.com
# Last modified 5/24/2014
#
#############################################################################
# This function collects a mailbox from the user. It checks that the mailbox exists and that the input results in only one mailbox.
Function GetMailbox
{
$mb = Read-Host "Alias of mailbox to retrieve folder permissions?"
$check = Get-Mailbox -Identity $mb -erroraction silentlycontinue
If ($check){
 $chk = $check.count
 If ($chk -and $chk -gt 1){
  Write-Host ""
  Write-Host "Please specify only one mailbox" -ForeGroundColor Yellow
  Write-Host ""
  GetMailbox
  }
  Else {
  Enumerate
  }
 }
 Else {
 Write-Host ""
 Write-Host "This is not a valid mailbox alias, please retry" -ForeGroundColor Red
 Write-Host ""
 GetMailbox
 }
}
# This function runs Get-MailboxFolderStatistics for the mailbox found in GetMailbox. It then takes the output and reformats it for a foreach loop that runs Get-MailboxFolderPermission for each folder path found
Function Enumerate
{
 Write-Host ""
 Write-Host "Analyzing mailbox" $check -ForeGroundColor Green
 Write-Host ""
$file = (".\" + $check.alias + "-" + $check.DisplayName + ".txt")
$mbfs = Get-MailboxFolderStatistics -Identity $check.Identity
$flist = $mbfs.folderpath
$flist | foreach {$chg = $_ -replace "/" , "\"
 $pchg = ($check.alias + ":" + $chg)
 $go = Get-MailboxFolderPermission -Identity $pchg -erroraction silentlycontinue
 If ($go) {
  Write-Host ""
  Write-Host "Folder permission for" $pchg -ForegroundColor Green
  $pchg | Out-File $file -append
  $go
  $go | Out-File $File -append
 }
 Else {}
 }
}
# After the functions are defined the script calls the first one
GetMailbox