How to Format a list to be emailed?

Tagged: 

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Alan Spillert Alan Spillert 2 years, 10 months ago.

  • Author
    Posts
  • #16261
    Profile photo of Alan Spillert
    Alan Spillert
    Participant

    With a number of searches I've put together a script that will email me a list of empty directories on our SAN. The email works, and sends me a rather ugly list on one line:

    [b]\\sann\rdb$\RDT00437 \\sann\rdb$\TEST0 \\sann\rdb$\TEST1 [/b]

    When I try to pipe it to FORMAT-LIST I get garbage (times 3):

    [b]Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData[/b]

    How can I format the list to look like:

    [b]\\sann\rdb$\TEST0
    \\sann\rdb$\TEST1
    \\sann\rdb$\TEST2[/b]

    Code:

    $mailto2 = "space.manager@xxxxxx.com
    $day_of_week = get-date -uformat "%A"
    $empty_dir = get-childitem \\sann\rdb$\ | Where-Object { $_.PSIsContainer } |
    Where-Object { $_.GetFiles().Count -eq 0 } |
    Where-Object { $_.GetDirectories().Count -eq 0 } | ForEach-Object {$_.FullName} | sort
    $smtpServer = "yyyyyyy.xxxxxx.com"
    $smtp = New-Object Net.Mail.SmtpClient($smtpServer)
    $msg = New-Object Net.Mail.MailMessage
    $msg.From = "abc@xxxxxx.com"
    $msg.Subject = $mailsubject + $day_of_week
    $msg.IsBodyHTML = $false
    $msg.Body = $empty_dir
    $msg.To.Add($mailto2)
    $smtp.Send($msg)

  • #16262
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    To answer your question, you are creating a string doing the for loop: ForEachObject{$_.FullName}

    Have you looked at using HTML reporting? Don Jones put together a free e-book on it and there are various other articles on Powershell HTML reporting. Basically:

    [ul]
    [li]Remove the ForEach logic[/li]
    [li]Update .IsBodyHTML to $true[/li]
    [li]Update .Body to ($empty_dir |ConvertTo-Html | Out-String) [/li]
    [/ul]

  • #16263
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    The Body parameter of Send-MailMessage (or property of the MailMessage class, in this case) takes a String, and you're passing it an Array. Arrays, when automatically converted to strings, are separated by the output field separator ($OFS), which defaults to a space.

    The simplest way to get what you see at the console is to pipe your array to Out-String before assigning it to the Body property:

    $msg.Body = $empty_dir | Out-String
    
  • #16266
    Profile photo of Alan Spillert
    Alan Spillert
    Participant

    Great! Thank you, Dave and Rob. Simple is best for this little weekly report.

You must be logged in to reply to this topic.