Home > Software design >  show Powershell variables and foreach output in email
show Powershell variables and foreach output in email

Time:11-23

I am trying to monitor specific folders of specific users mailboxes. My thought was to call the users using a variable and then run a foreach loop and send the output to an email so that it will be emailed to me.

Here is what I am starting with:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ExchangeServer/PowerShell -Authentication Kerberos 
Import-PSSession $Session -AllowClobber

$Users = 'user1','User2','user3','user4'

foreach($user in $users) {

    $message  = "------------- <br>"
    $message  ="checking user.... $user <br>"
    $message  = "------------- <br>"

    $messsage  = $report = Get-MailboxFolderStatistics $user | ?{$_.name -eq 'Top of Information Store' -or $_.name -eq 'Recoverable Items' -or $_.name -eq 'Deletions' -or $_.name -eq 'Purges' -or $_.name -eq 'Versions'}  | ft Name, ItemsInFolder, FolderAndSubFolderSize
   
}

Send-MailMessage -SmtpServer smtpserver.domain.com -From [email protected] -To [email protected] -Subject "Litigation Mailbox Size Report" -Body $message -BodyAsHtml

Get-PSSession | Remove-PSSession

I can get it to send me an email but all it has is the email is dashed lines with the users but not the results from the get-mailboxfolderstatistics. I have tried using the $report variable for the get-mailboxfolderstatistics and then not using it. Neither seem to work. Any help would be appreciated.

CodePudding user response:

The immediate explanation for your symptom is a typo: $messsage should be $message, as Santiago Squarzon points out.

  • To avoid such problems in scripts, consider setting Set-StrictMode -Version 1, which prevents references to nonexistent variables. Higher versions implement additional checks (which can be problematic - see GitHub issue #2798).

Even with the typo corrected, additional work is required:

You must use Out-String in order to embed a string rendering of the formatting instructions that Format-* cmdlets such as Format-Table (aliased to ft) output:

$message  = '<pre>{0}</pre>' -f (
  Get-MailboxFolderStatistics $user |
    Where-Object { $_.name -eq 'Top of Information Store' -or $_.name -eq 'Recoverable Items' -or $_.name -eq 'Deletions' -or $_.name -eq 'Purges' -or $_.name -eq 'Versions' } |
      Format-Table Name, ItemsInFolder, FolderAndSubFolderSize |
        Out-String
)

The above additionally wraps the output in a <pre> HTML element, so that the content renders with a monospaced font for proper column alignment.

Note: Out-String unexpectedly appends a trailing newline - see GitHub issue #14444. Add .TrimEnd() to the (...) expression to remove it, or .Trim() to also remove leading whitespace (empty lines).

  • Related