0

I have everything in place at least I think so. I want to email myself the output of a Get-WmiObject win32 command. example:

$OS = "."
(Get-WmiObject Win32_OperatingSystem).Name |Out-String

 $secpasswd = ConvertTo-SecureString "mypassword" -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential 
("support@myemail.com", $secpasswd)

    Send-MailMessage -To "support@myemail.com" -SmtpServer 
"smtp.office365.com" -Credential $mycreds -UseSsl "Backup Notification" -
Body $body -From "support@myemail.com"

I have tried the following:

$body = (
  Write-Host "Computer Info:" -Message $PCinfo
  ) -join "`r`n"
    Write-Verbose -Message $body

That returns the error: "Cannot validate argument on parameter 'Body'. The argument is null or empty."

Any direction, advice, or examples would be appreciated. Thanks

Wchristner
  • 117
  • 1
  • 3
  • 12

2 Answers2

2

This format give you some richer information. This takes the content of the Win32_OperatingSystem class and converts it into a HTML table, appending it to a $body variable, with your "Computer Info:" text above it:

$body = "Computer Info: <br>"
$body += Get-WmiObject -Class Win32_OperatingSystem | ConvertTo-HTML -Fragment

Effectively recreate $body by piping it to Out-String. This ensures it's a string object, which the -Body parameter of Send-MailMessage requires:

$Body = $Body | Out-String

Finally, when calling Send-MailMessage use the -BodyAsHTML parameter to ensure the email is sent as a HTML email:

Send-MailMessage -To "support@myemail.com" -From "support@myemail.com" -SmtpServer "smtp.office365.com" -Credential $mycreds -UseSsl "Backup Notification" -Body $body -BodyAsHTML
Robin
  • 1,602
  • 3
  • 16
  • 24
1

Write-Host bypasses the usual PowerShell data route (the pipeline); you may want to look into Get-Help Out-String or Get-Help Out-Default for possible alternatives.

In bypassing the pipeline with Write-Host, you leave the assignment to $body "empty" - that is, there is no data to assign to the variable. Since $null is a legal value for a variable to have, this will not throw an error, until the variable is used in a context where a null value is not permitted (such as with Send-MailMessage).

Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33