Kwagga
Kwagga

Reputation: 101

Email output of script

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
}

Upvotes: 0

Views: 14305

Answers (2)

Kwagga
Kwagga

Reputation: 101

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)

Upvotes: 2

Mehdi Jerbi
Mehdi Jerbi

Reputation: 51

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

Upvotes: 1

Related Questions