Search code examples
powershell-3.0

PowerShell Variable into SMTP email


I'd like to run the following for loop which works. Load it into a variable and send the results to an SMTP server. Any ideas on how to do it. Google isnt getting me anywhere.

$Servers = get-content C:\Server\server.txt

$To = "[email protected]"
$From = "[email protected]"
$SMTPserver = "mail.mail.com" 
$Subject="Server Status" 

$message = foreach($server in $servers) 
{
Get-WmiObject win32_processor -computername $server | select SystemName, 
LoadPercentage
} 

$smtp=new-object Net.Mail.SmtpClient($smtpServer) 
$smtp.Send($From, $To, $Subject, $Message) 

Solution

  • SmtpClient expects a message of type string however, if you run your query with the following Write-Host you are going to notice that $message is not of type string:

    $message = foreach($server in $servers) 
    {
        Get-WmiObject win32_processor -computername $server | select SystemName, 
        LoadPercentage
    } 
    
    Write-Host ("Message is of type " + ($message.GetType()))
    

    You can simply format message using e.g. Out-String to get a string like this:

    Write-Host ("Message " + ($message | Out-String))
    

    you can define it inline if you like or store the string message in a variable first:

    $smtp.Send($From, $To, $Subject, ($Message | Out-String) )