问题
I would like to email a list of AD users as a CSV but I don't want to have to save the CSV to disk before I email it.
Here is the code that gets me the data:
get-aduser -filter * -properties Telephonenumber |
where Telephonenumber -ne $Null |
select givenname, surname, telephonenumber |
sort surname
Now I want to add on something like:
| Export-Csv |
Send-MailMessage -From HelpDesk@company.com -to someone@company.com -subject "Outlook address book export" -SmtpServer EdgeTransport
Is there anyway to add the CSV data as an attachment in memory without saving the file to the file system?
回答1:
The -Attachments
parameter for Send-MailMessage
requires an array of paths, so you must write a file to disk somewhere.
To send your CSV data as the body of the email, use convertto-csv -notypeinformation
instead of export-csv
.
$myData = get-aduser -filter * -properties Telephonenumber | where Telephonenumber -ne $Null | select givenname, surname, telephonenumber | sort surname|convertto-csv -notypeinformation
Send-MailMessage -From HelpDesk@company.com -to someone@company.com -subject "Outlook address book export" -SmtpServer EdgeTransport -body $mydata
回答2:
The proposed/accepted answer above is incorrect and won't work. The -Body parameter of the Send-MailMessage expects an string object (System.String). The $mydata object created in the example is a System.array object. If you use it as shown above the command will fail.
What you can do is create a file, fill it with the CSV data, email it as an attachment and then delete it.
Using your code above, for example:
$attachment = New-Item filename.csv -ItemType file
get-aduser -filter * -properties Telephonenumber | where Telephonenumber -ne $Null | select givenname, surname, telephonenumber | sort surname | Export-Csv $attachment -NoTypeInformation
Send-MailMessage -Attachments $attachment -Body $SmtpBodyTrue -BodyAsHtml -From $SmtpSender -To $MailTo -Subject $SmtpSubject -SmtpServer $SmtpServer
Remove-Item $attachment
$attachment = $null
回答3:
I know this is a super old thread, but the above answers are no longer correct. You can send in-memory objects as attachments without writing to a file first. You need to use .net methods, but it works well.
The key is the .net method [System.Net.Mail.Attachment]::CreateAttachmentFromString
http://geekswithblogs.net/mkoerner/archive/2012/01/19/powershell-emailing-strings-as-attachments.aspx
来源:https://stackoverflow.com/questions/13648761/how-can-i-chain-export-csv-to-send-mailmessage-without-having-to-save-the-csv-to