# Define path for HTML report $outputFile = "$env:USERPROFILE\Downloads\SharedMailboxMessageCopySettingsReport(Navitas).html" # Define path for server address and credentials $serverAddressFile = ".\DefaultServer.txt" $credentialFile = ".\AdminCredential.xml" # --- HTML Styling (CSS) --- $cssStyle = @" "@ # --- Script Logic --- $session = $null # Initialize session variable # --- Initialize Report Body with Title and Descriptions --- # Start with the main H1 title $reportBody = "

Shared Mailbox Message Copy Settings Report

" # Define and add the descriptions right after the title $descriptionHtml = @"

Understanding Message Copy Settings:

This script reports on these settings and allows enabling 'SentAs Message Copy' (MessageCopyForSentAsEnabled = $true) in bulk.

"@ $reportBody += $descriptionHtml try { # --- Input Validation --- if (-not (Test-Path $serverAddressFile)) { throw "Server address file not found: $serverAddressFile" } if (-not (Test-Path $credentialFile)) { throw "Credential file not found: $credentialFile" } # Import admin credentials $serverAddress = Get-Content -Path $serverAddressFile $credential = Import-Clixml -Path $credentialFile # Establish session with Exchange Server Write-Host "Connecting to Exchange Server: $serverAddress..." $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$serverAddress/PowerShell/" -Authentication Kerberos -Credential $credential -ErrorAction Stop Import-PSSession $session -DisableNameChecking -ErrorAction Stop Write-Host "Successfully connected to Exchange." -ForegroundColor Green # --- Data Retrieval --- Write-Host "Retrieving shared mailboxes..." $mailboxes = Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize Unlimited | Select-Object DisplayName, PrimarySmtpAddress, MessageCopyForSendOnBehalfEnabled, MessageCopyForSentAsEnabled -ErrorAction Stop Write-Host "Found $($mailboxes.Count) shared mailboxes." # --- Generate "BEFORE" Report Section --- # This will append to the existing $reportBody (which already has Title + Description) $reportBody += "

Shared Mailbox Message Copy Settings BEFORE Update

" if ($mailboxes.Count -gt 0) { $formattedMailboxesBefore = $mailboxes | Select-Object DisplayName, PrimarySmtpAddress, @{Name='SendOnBehalfEnabled';Expression={$_.MessageCopyForSendOnBehalfEnabled}}, @{Name='SentAsEnabled';Expression={$_.MessageCopyForSentAsEnabled}} $htmlFragmentBefore = $formattedMailboxesBefore | ConvertTo-Html -Fragment -Property DisplayName, PrimarySmtpAddress, @{Label='SendOnBehalf Message Copy'; Expression = {"$($_.SendOnBehalfEnabled)"}}, @{Label='SentAs Message Copy'; Expression = {"$($_.SentAsEnabled)"}} $reportBody += [System.Net.WebUtility]::HtmlDecode($htmlFragmentBefore) } else { $reportBody += "

No shared mailboxes found.

" } # --- Filter Mailboxes for Update --- $mailboxesToUpdate = $mailboxes | Where-Object { $null -ne $_.MessageCopyForSentAsEnabled -and [bool]($_.MessageCopyForSentAsEnabled) -eq $false } # --- Update Logic --- if ($mailboxesToUpdate.Count -gt 0) { Write-Host "$($mailboxesToUpdate.Count) mailboxes identified with SentAs Message Copy disabled:" -ForegroundColor Yellow $mailboxesToUpdate | ForEach-Object { Write-Host " - $($_.DisplayName) ($($_.PrimarySmtpAddress))" } $response = Read-Host "Do you want to ENABLE SentAs Message Copy for these $($mailboxesToUpdate.Count) shared mailboxes? (Y/N)" if ($response -eq 'Y') { Write-Host "Starting update process..." $updateLog = foreach ($mb in $mailboxesToUpdate) { $updateStatus = "OK" $updateMessage = "Successfully enabled SentAs Message Copy for $($mb.DisplayName) ($($mb.PrimarySmtpAddress))." try { Set-Mailbox -Identity $mb.PrimarySmtpAddress -MessageCopyForSentAsEnabled $true -ErrorAction Stop Write-Host $updateMessage -ForegroundColor Green } catch { $updateStatus = "Error" $updateMessage = "Failed to enable SentAs Message Copy for $($mb.DisplayName) ($($mb.PrimarySmtpAddress)). Error: $($_.Exception.Message)" Write-Host $updateMessage -ForegroundColor Red } [PSCustomObject]@{ Mailbox = "$($mb.DisplayName) ($($mb.PrimarySmtpAddress))" Status = $updateStatus Details = $updateMessage } } $reportBody += "

Update Results

" $reportBody += $updateLog | ConvertTo-Html -Fragment -Property Mailbox, Status, Details Write-Host "Waiting 5 seconds for changes to apply..." Start-Sleep -Seconds 5 # --- Generate "AFTER" Report Section --- Write-Host "Retrieving updated shared mailbox settings..." $updatedMailboxes = Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize Unlimited | Select-Object DisplayName, PrimarySmtpAddress, MessageCopyForSendOnBehalfEnabled, MessageCopyForSentAsEnabled -ErrorAction Stop $reportBody += "

Shared Mailbox Message Copy Settings AFTER Update

" if ($updatedMailboxes.Count -gt 0) { $formattedMailboxesAfter = $updatedMailboxes | Select-Object DisplayName, PrimarySmtpAddress, @{Name='SendOnBehalfEnabled';Expression={$_.MessageCopyForSendOnBehalfEnabled}}, @{Name='SentAsEnabled';Expression={$_.MessageCopyForSentAsEnabled}} $htmlFragmentAfter = $formattedMailboxesAfter | ConvertTo-Html -Fragment -Property DisplayName, PrimarySmtpAddress, @{Label='SendOnBehalf Message Copy'; Expression = {"$($_.SendOnBehalfEnabled)"}}, @{Label='SentAs Message Copy'; Expression = {"$($_.SentAsEnabled)"}} $reportBody += [System.Net.WebUtility]::HtmlDecode($htmlFragmentAfter) } else { $reportBody += "

Could not retrieve updated mailbox information.

" } Write-Host "Bulk update process completed." -ForegroundColor Green $reportBody += "

Bulk update process completed.

" } else { Write-Host "Bulk update canceled by user. No changes were made." -ForegroundColor Yellow $reportBody += "

Bulk update canceled by user. No changes were made.

" } } else { Write-Host "No shared mailboxes found requiring an update (SentAs Message Copy is already enabled or mailbox property is null)." -ForegroundColor Green $reportBody += "

No shared mailboxes required an update for the 'SentAs Message Copy' setting.

" } } catch { Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red # Append error details to the report body (which already has title/description) $reportBody += "

Script Execution Error

" $reportBody += "

An error occurred while processing shared mailbox settings.

" $reportBody += "

Error Details:
$([System.Net.WebUtility]::HtmlEncode($_.Exception.Message))

" if ($_.Exception.StackTrace) { $reportBody += "

Stack Trace:
$([System.Net.WebUtility]::HtmlEncode($_.Exception.StackTrace) -replace "`n", "
")

" } if ($_.InvocationInfo) { $reportBody += "

Script Line: $($_.InvocationInfo.ScriptLineNumber)

" } } finally { # --- Generate Final HTML Report --- $reportFooter = "

Report generated on: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') by $($env:USERNAME)

" # Assemble the full HTML page # Use -Body for the content we built. No -PreContent needed now. ConvertTo-Html -Head $cssStyle ` -Title "Shared Mailbox Message Copy Settings Report" ` -Body $reportBody ` -PostContent $reportFooter | Out-File $outputFile -Encoding UTF8 -ErrorAction SilentlyContinue # Check if the file was actually created before trying to open it if (Test-Path $outputFile) { Write-Host "HTML Report saved to: $outputFile" Invoke-Item -Path $outputFile } else { Write-Host "Failed to create the report file at: $outputFile" -ForegroundColor Red } # Clean up Exchange session if ($session -ne $null) { Write-Host "Removing Exchange PSSession..." Remove-PSSession $session Write-Host "Session removed." } }