Wchristner
Wchristner

Reputation: 187

get wmiobject win32: how do I email the output

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 
("[email protected]", $secpasswd)

    Send-MailMessage -To "[email protected]" -SmtpServer 
"smtp.office365.com" -Credential $mycreds -UseSsl "Backup Notification" -
Body $body -From "[email protected]"

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

Upvotes: 0

Views: 438

Answers (2)

Robin
Robin

Reputation: 1645

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 "[email protected]" -From "[email protected]" -SmtpServer "smtp.office365.com" -Credential $mycreds -UseSsl "Backup Notification" -Body $body -BodyAsHTML

Upvotes: 2

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10799

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).

Upvotes: 1

Related Questions