首页 > 解决方案 > powershell 和使用脚本接收邮件的问题

问题描述

我是powershell的新手。:( 但是我正在使用带有 gmail 邮件服务器的 powershell 配置邮件通知,一切正常,但我想在邮件正文中添加脚本的输出。

这是要使用的命令的图像

$username   = 'test@gmail.com'
$password   = '*****'
$secstr     = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$body = C:\Users\esanchez\Desktop\script.ps1
$hash = @{
    from       = "test@gmail.com"
    to         = "receptor@gmail.com"
    subject    = "test"
    smtpserver = "smtp.gmail.com"
    port       = "587"
    body       = GU
    credential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
    usessl     = $true
    verbose    = $true
}

Send-MailMessage  -body $body @hash

标签: windowspowershell

解决方案


是否C:\Users\esanchez\Desktop\script.ps1包含图像中显示的脚本?如果是这样,我认为你很接近。只需将该行更改为包含| Out-String| ConvertTo-Html -Fragment在末尾,以便它将您的输出转换为您可以在正文中发送的内容,然后更新正文$hash以使用$body。最后修复实际的命令行

$username   = 'test@gmail.com'
$password   = '*****'
$secstr     = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$body = C:\Users\esanchez\Desktop\script.ps1 | Out-String  # or | ConvertTo-Html -Fragment 
$hash = @{
    from       = "test@gmail.com"
    to         = "receptor@gmail.com"
    subject    = "test"
    smtpserver = "smtp.gmail.com"
    port       = "587"
    body       = $body   # update to use $body
    credential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
    usessl     = $true
    verbose    = $true
}

Send-MailMessage  @hash  # remove body parameter here since you are already passing it in with the hashtable

推荐阅读