Using pipeline object to populate mail -to and -attachment

Viewed 246

First ever Powershell script so any advice or recommendations are appreciated. I'm parsing a .csv into smaller .csv's to send out information about servers to recipients and i'm running into a problem in my foreach. How do I get this to work?

One interesting thing is that in Send-MailMessage, -to should not accept pipeline objects, It still throws an error, but it still sends the emails. However the attachment will never send.

    #had to set this as a variable because @ was throwing splatting errors
    $Mail = "@Email.com"

    #Import csv and split information, exports UID.csv
    Import-csv C:\path\info.csv | Group-Object UID |    
      ForEach-Object {
        $_.Group | Export-csv "C:\path\$($_.Name).csv" -NoTypeInformation
      }

    #Import file again to get unique list of UID and send mail with 
    #respective UID.csv

    Import-csv C:\path\info.csv | Group-Object UID |    
      ForEach-Object {
        $_.UID | Send-MailMessage -From "<Me@email.com>" -To "<$($_.Name)$Mail>" `
          -Attachments "C:\path\$($_.Name).csv" `
          -Subject "Testing" -Body "Please Ignore This" -Priority High `
          -SmtpServer smtp.server.com   
      }
1 Answers

in Send-MailMessage, -to should not accept pipeline objects

In principle it does, namely if the pipeline objects have a .To property (which is not the case for you).

However, with your current approach, you don't need pipeline input at all, given that you're supplying all input as arguments.

Additionally, your pipeline input is incorrect, because $_.UID sends $null through the pipeline, given that $_ - a group-info object output by Group-Object - doesn't have a .UID property.

Using delay-bind script blocks ({ ... }), you can simplify your command as follows, obviating the need for a ForEach-Object call:

Import-csv C:\path\info.csv | Group-Object UID |
  Send-MailMessage -From "<Me@email.com>" -To { "<$($_.Name)@Email.com>" } `
      -Attachments { "C:\path\$($_.Name).csv" } `
      -Subject "Testing" -Body "Please Ignore This" -Priority High `
      -SmtpServer smtp.server.com   

In short, the script blocks passed to -To and Attachments are evaluated for each input object, and their output determines the parameter value in each iteration. In the script block, $_ represents the pipeline object at hand, as usual.

Note that such delay-bind script blocks can only be used with parameters that are designed to accept pipeline input (irrespective of whether by value (whole object) or by a specific property's value).

Related