0

I'm trying to email the output of a script, but I'm pretty sure I have my syntax all mixed up.

Here what I'd like:

send-mailmessage -from " Daily Check <[email protected]>" -to "Admin <[email protected]>" -subject "Daily Check: Server Times" -body $output -priority High -dno onSuccess, onFailure -smtpServer mail.company.com

$output=

{
ForEach ($server in $servers) {
    $time = ([WMI]'').ConvertToDateTime((gwmi win32_operatingsystem -computername $server).LocalDateTime)
    $server + '  ' + $time
    }        
}
$servers = 'SVRADFS365', 'SVRAPP01', 'SVRCAS01', 'SVRCAS02

The original script whose output I want emailed:

$servers = 'server1', 'server2', 'server3', 'server4'
ForEach ($server in $servers) {
    $time = ([WMI]'').ConvertToDateTime((gwmi win32_operatingsystem -computername $server).LocalDateTime)
    $server + '  ' + $time
}

2 Answers 2

2

Got it working...

If you get the error:

Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported.
At line:11 char:150
+ ... r Times" -body ($output ) -priority High -dno onSuccess, onFailure -smtpServer m ...
+                    ~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.SendMailMessage

Add: -body ($output | Out-String)

1

You must create $output before sending your email by send-mailmessage cmdlet.

Try with this code:

$servers = 'SVRADFS365', 'SVRAPP01', 'SVRCAS01', 'SVRCAS02'
$output = ForEach ($server in $servers) {
            $time = ([WMI]'').ConvertToDateTime((gwmi win32_operatingsystem -computername $server).LocalDateTime)
            $server + ' ' + $time
          }

send-mailmessage -from " Daily Check <[email protected]>" -to "Admin <[email protected]>" -subject "Daily Check: Server Times" -body $output -priority High -dno onSuccess, onFailure -smtpServer mail.company.com
1
  • I tried what you recommended, it works, but the ForEach only runs once. ' $servers = 'SVRADFS365', 'SVRAPP01', 'SVRCAS01', 'SVRCAS02' $output= "{ ForEach ($server in $servers) { $time = ([WMI]'').ConvertToDateTime((gwmi win32_operatingsystem -computername $server).LocalDateTime) $server + ' ' + $time } }" send-mailmessage -from " Daily Check" -to "Admin" -subject "Daily Check: Server Times" -body $output -priority High -dno onSuccess, onFailure -smtpServer mail.company.com'
    – Kwagga
    Jan 6, 2015 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.