gpt4 book ai didi

powershell - Azure Runbook 输出到电子邮件

转载 作者:行者123 更新时间:2023-12-02 23:58:01 24 4
gpt4 key购买 nike

我正在尝试将 VM 状态的输出从 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="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0668697463766a7f466f626a63647f7263752865696b" rel="noreferrer noopener nofollow">[email protected]</a>", #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 "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a7a2abafa886afa2aaa3a4bfb2a3b5e8a5a9ab" rel="noreferrer noopener nofollow">[email protected]</a>" -Body "$VMStatus" -Subject "vm0 Status"

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

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

最佳答案

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

下面是一个例子:

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

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

关于powershell - Azure Runbook 输出到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37948614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com