Reputation: 5294
I'm trying to read the content of a text file into a string variable with powershell in order to use it to send an email (via smtp).
Using Get-Content
I have no problem reading the contents of a file into a variable:
$body = Get-Content 'C:\somewhere\some-file.html'
The problem is
Send-MailMessage -To [recipient] -From [sender] -Subject [subject] -Body $body -SmtpServer [ip address]
fails with the message
Cannot convert 'System.Object[]' to 'System.String' required by 'Body' parameter. Specified method not supported.
How can I get the file contents into the variable as a String
? I've tried converting the resulting Object[]
array to a String
by piping the $body
variable with Convert-String
but with no success.
Edit
To anyone looking for a one-liner, with the help of Mark's answer below here it is:
Send-MailMessage -To [email protected] -From [email protected] -Subject "Test" -Body (Get-Content 'C:\somewhere\some-file.html' | Out-String) -SmtpServer 123.456.789.012 -BodyAsHtml
Upvotes: 1
Views: 5195
Reputation: 23355
Try:
$body = Get-Content 'C:\somewhere\some-file.html' | Out-String
The problem is probably that Get-Content
is creating an array of strings and the -Body
parameter is expecting a single string.
The Out-String
cmdlet I think would convert it to a single string.
Upvotes: 2