【问题标题】:Azure runbook output to emailAzure Runbook 输出到电子邮件
【发布时间】:2016-10-23 05:58:59
【问题描述】:

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

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'

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

【问题讨论】:

    标签: powershell azure automation runbook


    【解决方案1】:

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

    下面是一个例子:

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

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

    【讨论】:

      【解决方案2】:

      请更改

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

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

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

      【讨论】:

      • 嗯。仍然没有运气。不知道我错过了什么。我使用了提到的格式。 $Body = Get-AzureRmVM -Name "vm0" -ResourceGroupName "TestRG" -Status |选择-展开状态
      猜你喜欢
      • 2012-10-04
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多