VMware Cloud Community
mcamp001
Contributor
Contributor
Jump to solution

send script results via email

ok, time to reach out for a bit of help;

I am looking to receive a daily, or weekly report of the reported time on all of my hosts. I have pieced together code (below), but at this point I am getting a blank email for every host. The script runs and outputs to the command window ok, but I want to receive just one email, with the reported result of all hosts. When executing this now, the command window reports 'Time on $host1 within allowed range' if it is within range of course, or offers the time offset.

I have serached and tried various methods of invoking this send mail function, but can someone take a look and recommend a better way?

script:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

$allowedDifferenceSeconds = 20

get-view -ViewType HostSystem -Property Name, ConfigManager.DateTimeSystem | %{   
    #get host datetime system
    $dts = get-view $_.ConfigManager.DateTimeSystem
   
    #get host time
    $t = $dts.QueryDateTime()
   
    #calculate time difference in seconds
    $s = ( $t - [DateTime]::UtcNow).TotalSeconds
   
    #check if time difference is too much
    if([math]::abs($s) -gt $allowedDifferenceSeconds){
        #print host and time difference in seconds
        $row = "" | select HostName, Seconds
        $row.HostName = $_.Name
        $row.Seconds = $s
        $row
    }
    else{
        Write-Host "Time on" $_.Name "within allowed range"

$smtpSrv = "smtp.domain.com"
$from = "vmwaretimepolice@domain.com"
$to = "recieipt@domain.com"
$subject = "VM Host Time Report"


$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)

$smtp = new-object Net.Mail.SMTPclient($smtpSrv)

$smtp.send($msg)

}

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Try something like this

$allowedDifferenceSeconds = 20 
$body = $null

get-view
-ViewType HostSystem -Property Name, ConfigManager.DateTimeSystem | %{     #get host datetime system
    $dts = get-view $_.ConfigManager.DateTimeSystem     #get host time
    $t = $dts.QueryDateTime()     #calculate time difference in seconds
    $s = ( $t - [DateTime]::UtcNow).TotalSeconds     #check if time difference is too much
    if([math]::abs($s) -gt $allowedDifferenceSeconds){         #print host and time difference in seconds
        $body += ("On " + $_.Name + " the time difference is "  + $s + " seconds`r" | Out-String)     }     else{         $body +=  ("Time on " + $_.Name + " within allowed range`r" | Out-String)     } } $smtpSrv = "smtp.domain.com"
$from = "vmwaretimepolice@domain.com"
$to = "recieipt@domain.com"
$subject = "VM Host Time Report" $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $smtp = new-object Net.Mail.SMTPclient($smtpSrv) $smtp.send($msg)


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
19 Replies
LucD
Leadership
Leadership
Jump to solution

You don't put anything in the Body of the email.

What do you want to place in there ?

Btw, if you are using PowerShell v2 (which you should), you can use the Send-MailMessage cmdlet.

Do a

Get-Help Send-MailMessage -Full

to see all the options.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
LucD
Leadership
Leadership
Jump to solution

An educated guess, is this producing what you are looking for ?

$allowedDifferenceSeconds = 20
$body = @() get-view -ViewType HostSystem -Property Name, ConfigManager.DateTimeSystem | %{     #get host datetime system
    $dts = get-view $_.ConfigManager.DateTimeSystem     #get host time
   
$t = $dts.QueryDateTime()     #calculate time difference in seconds
   
$s = ( $t - [DateTime]::UtcNow).TotalSeconds     #check if time difference is too much
   
if([math]::abs($s) -gt $allowedDifferenceSeconds){         #print host and time difference in seconds
       
$row = "" | select HostName, Seconds         $row.HostName = $_.Name         $row.Seconds = $s
       
$body += $row
    }    
else{         Write-Host "Time on" $_.Name "within allowed range"
    } } $smtpSrv = "smtp.domain.com"
$from = "vmwaretimepolice@domain.com"
$to
= "recieipt@domain.com"
$subject
= "VM Host Time Report" $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $smtp = new-object Net.Mail.SMTPclient($smtpSrv) $smtp.send($msg)


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

Thanks Luc for the fast replies.

This is close, I would like to see in the body of the email what the script reports when running just in a command window. For example, the script goes to each host and checks the time and then reports if it is within the parameters.

For the email body, I would like to see something like;

time on host1 within allowed range

time on host2 within allowed range

time on host3 within allowed range

etc

Also, is there a way to just send the results via email and not have the script run in the command window?- ignore this, wasn't thinking

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Try something like this

$allowedDifferenceSeconds = 20 
$body = $null

get-view
-ViewType HostSystem -Property Name, ConfigManager.DateTimeSystem | %{     #get host datetime system
    $dts = get-view $_.ConfigManager.DateTimeSystem     #get host time
    $t = $dts.QueryDateTime()     #calculate time difference in seconds
    $s = ( $t - [DateTime]::UtcNow).TotalSeconds     #check if time difference is too much
    if([math]::abs($s) -gt $allowedDifferenceSeconds){         #print host and time difference in seconds
        $body += ("On " + $_.Name + " the time difference is "  + $s + " seconds`r" | Out-String)     }     else{         $body +=  ("Time on " + $_.Name + " within allowed range`r" | Out-String)     } } $smtpSrv = "smtp.domain.com"
$from = "vmwaretimepolice@domain.com"
$to = "recieipt@domain.com"
$subject = "VM Host Time Report" $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $smtp = new-object Net.Mail.SMTPclient($smtpSrv) $smtp.send($msg)


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

I am still gettting a body that's blank, no info. I think where I'm getting confused is how to put the outputed data into the email body. 

0 Kudos
LucD
Leadership
Leadership
Jump to solution

This does return hostsystem objects ?

get-view -ViewType HostSystem -Property Name, ConfigManager.DateTimeSystem

The lines are placed in the variable $body.

The content of this variable is then used as the mail body.

It looks as if the variable $body stays empty.

Try changing

$body = $null

with

$body = "Test"

at the beginning of the script. Do you see that text in the mail body ?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

the line you outline produces this when run from the command prompt:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

[vSphere PowerCLI] C:\data\scripts\powerCLI> get-view -ViewType HostSystem -Property
Name, ConfigManager.DateTimeSyst
Get-View : 9/14/2011 12:43:43 PM    Get-View        Invalid property: ConfigManager.
DateTimeSyst
At line:1 char:9
+ get-view <<<<  -ViewType HostSystem -Property Name, ConfigManager.DateTimeSyst
    + CategoryInfo          : InvalidArgument: (:) [Get-View], InvalidArgument
    + FullyQualifiedErrorId : Client20_MoServiceImpl_GetNetInteropView_InvalidPrope
   rty,VMware.VimAutomation.ViCore.Cmdlets.Commands.DotNetInterop.GetVIView

Get-View : 9/14/2011 12:43:43 PM    Get-View        Server server1.domain.c
om not connected.
At line:1 char:9
+ get-view <<<<  -ViewType HostSystem -Property Name, ConfigManager.DateTimeSyst
    + CategoryInfo          : InvalidArgument: (:) [Get-View], ViServerConnectionEx
   ception
    + FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_TryVerifyIsConnected
   _NotConnected,VMware.VimAutomation.ViCore.Cmdlets.Commands.DotNetInterop.GetVIV
  iew

[vSphere PowerCLI] C:\data\scripts\powerCLI>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.>>>>>>>>>>>>>>>>>>>>>>>

when changing $null to "test", I do see the word test in the email body now

the top portion of my original example returns results when run from the command prompt. I just want to get that output into the body of the email.

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Oops, that should be System at the end, not Syst.

It's corrected now.

The 2nd error message says that you are not connected.

Did you do a Connect-VIServer before running the script ?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

thanks Luc for hanging in there on this one. I will simplfy what I am asking. I have attached a script 'time-check3.ps1', when I run this from the command line I receive the output of:

Time on host1.domain.com within allowed range (assuming it is within the allowed range, if not it shows offset in secs)

All I am trying to do is schedule this script to run and send me the output via email. The same result I receive in the command window would be fine in the email body.

Hope this helps clarify. And the Vcenter server error I believe was because I ran that particular one in 32 bit mode, it does not happen in 64bit mode.

Thanks!

0 Kudos
LucD
Leadership
Leadership
Jump to solution

The attached script only shows output on the console ($row and the Write-Host cmdlet).

The script I gave you stores the results in a variable $body and then passed this variable as the body of the email.

That works for me. Which script do you use when you receive the empty email ? The attached one or the last script I gave you ?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

you are correct, the script I attached only does console output. I want to take that output to email.

I ran the script(s) you provided, but the email body I receive is blank. 

0 Kudos
LucD
Leadership
Leadership
Jump to solution

In my 2nd script, comment out these lines

$smtpSrv = "smtp.domain.com"
$from = "vmwaretimepolice@domain.com"
$to = "recieipt@domain.com"
$subject = "VM Host Time Report" $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $smtp = new-object Net.Mail.SMTPclient($smtpSrv) $smtp.send($msg)

and replace them by just

$body

Do you get anything on screen ?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

I do not get anything on the screen

0 Kudos
LucD
Leadership
Leadership
Jump to solution

And this returns all your ESX(i) servers ?

get-view -ViewType HostSystem -Property Name, ConfigManager.DateTimeSystem


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

yes, sinpet of the results:

Name                : host.domain.com
DisabledMethod      :
RecentTask          :
DeclaredAlarmState  :
TriggeredAlarmState :
AlarmActionsEnabled : False
Tag                 :
Value               :
AvailableField      :
MoRef               : HostSystem-host-93128
Client              : VMware.Vim.VimClient

Runtime             :
Summary             :
Hardware            :
Capability          :
ConfigManager       : VMware.Vim.HostConfigManager
Config              :
Vm                  :
Datastore           :
Network             :
DatastoreBrowser    :
SystemResources     :
Parent              :
CustomValue         :
OverallStatus       : gray
ConfigStatus        : gray
ConfigIssue         :
EffectiveRole       :
Permission          :

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Strange, the script works in my environment.

I'll have another look.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

ok, a bit more information.

when I run the attached script from the PowerCLI command prompt, it works fine

when I run this from the powershell command prompt, I do get the email, but the body is blank.

hence, when I try to put this into task scheduler using powershell (powershell -command "& 'c:\data\scripts\powercli\host-time-check.ps1' "), same result, blank email.

So I guess the real question is one of two things:

1) how can I run this via powercli in the windows task scheduler (if this is possible)

or

2) how can I get this to work when using powershell?

Thanks!

0 Kudos
LucD
Leadership
Leadership
Jump to solution

You have to make sure the PowerCLI is loaded before you use any of the PowerCLI cmdlets.

Add the following line to your script

Add-PSSnapin VMware.VimAutomation.Core

Also make sure that you are connected to the vSphere server.

Add a

Connect-VIServer MyVC

to the script.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mcamp001
Contributor
Contributor
Jump to solution

Well, through a combination of ideas represented here, I finally have this working. Thanks a bunch for helping me out with this!

0 Kudos