Azure Runbook输出到电子邮件

时间:2016-06-21 15:28:41

标签: powershell azure automation runbook

我正在尝试将Azure状态的输出从Azure自动化Runbook发送到电子邮件中,我使用以下代码:

function Send-EMail {
Param (
    [Parameter(Mandatory=$true)]
    [String]$EmailTo,
    [Parameter(Mandatory=$true)]
    [String]$Subject,
    [Parameter(Mandatory=$true)]
    [String]$Body,
    [Parameter(Mandatory=$false)]
    [String]$EmailFrom="noreply@idlebytes.com",  #This gives a default value to the $EmailFrom command
    [parameter(Mandatory=$false)]
    [String] $SmtpServer = (Get-AutomationVariable -Name 'SmtpHost'),
    [parameter(Mandatory=$false)]
    [String] $SmtpUsername = (Get-AutomationVariable -Name 'SmtpUsername'),
    [parameter(Mandatory=$false)]
    [String] $SmtpPassword = (Get-AutomationVariable -Name 'SmtpPassword')
)

    $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 
    $SMTPClient.EnableSsl = $true 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($SmtpUsername, $SmtpPassword); 
    $SMTPClient.Send($SMTPMessage)
    Remove-Variable -Name SMTPClient
    Remove-Variable -Name SmtpPassword

} #End Function Send-EMail

$AutomationCredentialAssetName = "PScredential"

# Get the credential asset with access to my Azure subscription
$Cred = Get-AutomationPSCredential -Name $AutomationCredentialAssetName

# Authenticate to Azure Service Management and Azure Resource Manager

Add-AzureRmAccount -Credential $Cred | Out-Null

$VMStatus = Get-AzureRmVM -Name "vm0" -ResourceGroupName "TestRG" -Status


Send-EMail -EmailTo "admin@idlebytes.com" -Body "$VMStatus" -Subject "vm0 Status"

我希望电子邮件输出打印输出的确切状态,然后打印对象Microsoft.Azure.Commands.Compute.Models.PSVirtualMachineInstanceView'

有人可以帮忙,如何将对象内容作为电子邮件中的字符串获取?

2 个答案:

答案 0 :(得分:1)

将变量引用(例如$ MyVar)添加到电子邮件正文中,默认情况下它只返回对象类型,其中PowerShell中的输出是一种特殊的管道活动,将内容呈现为列表或表格。为了在电子邮件中包含内容,我们必须单独引用不同的属性。

以下是一个例子:

[string]$EmailBody = (“Property 1 = [{0}], Property 2 = [{1}], Property 3 = [{2}]” -f $MyObject.Property1, $MyObject.Property2, $MyObject.Property3)

上面的行将设置变量$ EmailBody,它是一个字符串,包含一个名为$ MyObject的对象变量的三个属性。如果我们只是引用$ MyObject for PowerShell输出,则会显示所有属性,但要在电子邮件中包含这些属性,我们必须单独引用它们。

答案 1 :(得分:0)

请更改

$VMStatus = Get-AzureRmVM -Name "vm0" -ResourceGroupName "TestRG" -Status

$VMStatus = Get-AzureRmVM -Name "vm0" -ResourceGroupName "TestRG" -Status | select -expand Statuses

第一个命令返回PSVirtualMachineInstanceView对象,而第二个命令返回一个字符串数组。