How to use the vCenter Server Settings from PowerCLI to send e-mail
November 19, 2011 3 Comments
If you use PowerCLI to generate reports and send those reports to you via e-mail, you probably have the sender e-mail adress and the smtp server hard coded in your script. But what if one of those changes? You will have to modify all your scripts. Wouldn’t it be easier if you have stored them in one place, so you have to change them only once?
You can put the sender e-mail adress and the smtp server in the vCenter Server Mail Sender Settings.
Figure 1. vCenter Server Mail Sender Settings.
With PowerCLI you can retrieve the values from the vCenter Server Settings and use them in your scripts. If your smtp server address or your sender e-mail address changes, you have to change them only in the vCenter Server Settings and all your PowerCLI scripts remain working. Isn’t that nice?
The following PowerCLI script shows you how to retrieve the mail.sender and mail.smtp.server values from the vCenter Server Settings. And it uses the Send-MailMessage cmdlet to send you an overview of all your virtual machines.
$vCenterSettings = Get-View -Id 'OptionManager-VpxSettings' $MailSender = ($vCenterSettings.Setting | Where-Object { $_.Key -eq "mail.sender"}).Value $MailSmtpServer = ($vCenterSettings.Setting | Where-Object { $_.Key -eq "mail.smtp.server"}).Value $Report = Get-VM | Sort-Object -Property Name | Out-String Send-MailMessage -from $MailSender -to "you@yourdomain.com" -subject "Sending the vSphere report" -body $Report -smtpServer $MailSmtpServer
Listing 1. PowerCLI script to retrieve the mail sender and smtp server from the vCenter Server Settings and send an e-mail using them.
Nice trick.
An alternative is to put the SMTP server in the $PSEmailServer variable in one of your profiles.
Then you don’t need to use the -SmtpServer parameter on the Send-MailMessage cmdlet.
Provided of course you only have 1 SMTP server in your environment.
How come the script given works perfectly fine, but my triggered alarm won’t send the e-mail…??
That Is cool idea