首页 > 解决方案 > Send-MailMessage 参数 Null 或空

问题描述

有人可以帮我弄清楚这部分。

#Mail Configuration
$smtpUser = "email@domain.com"
$smtppass = ConvertTo-SecureString "PasswordAsPlainText" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($smtpuser, $smtppass)
$ToAddress = "toaddress@domain.com"
$FromAddress = "send@domain.com"
$SMTPSERVER = "smtp.office365.com"
$SMTPPORT = "587"

$MailParam = @{
        To = $ToAddress
        From = $FromAddress
        Subject = $subject
        Body = $Mail
        SMTPServer = $SMTPServer
        Port = $SMTPPORT
        Credential = $pscred
        }
#Send Email
$GetChildItem = Get-ChildItem -Path C:\Temp
if ($GetChildItem -ne $Null)
    {
    Write-Host "Backup Success"
    $subject = "$env:COMPUTERNAME SQL Backup Success"
    $Mail = "SQL Backup Succeded on the server, please see the attached report for more details"
    $attachment = $reportfile
    Send-MailMessage @MailParam -BodyAsHtml -usessl
   #Exit
    }
if ($GetChildItem -eq $Null)
    {
    Write-Host "Backup Failed"
    $subject = "$env:COMPUTERNAME SQL Backup Failed"
    $Mail = "SQL Backup Failed on the server, please see the attached report for more details"
    $attachment = $reportfile, $debuglog
    Send-MailMessage @MailParam -usessl -BodyAsHtml
    #Exit
    }

现在我认为上面的代码没有任何问题,我不是专业的编码员,但我几乎可以复制和粘贴 :) 并从那里获取东西以使其为我工作。

上面代码的问题是,当运行它时,它第一次不起作用,但当你再次运行它时,它工作正常。你第一次得到的错误是

Send-MailMessage:无法验证参数“正文”上的参数。参数为 null 或空。提供一个不为 null 或空的参数,然后重试该命令。在 C:\Users\Aasim\Desktop\Untitled1.ps1:29 char:26 + Send-MailMessage @MailParam -BodyAsHtml -usessl + ~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Send- MailMessage],ParameterBindingValidationException + FullyQualifiedErrorId:ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage

我不确定问题是什么,以及为什么它只在第一次时不起作用,但在您关闭并重新打开脚本之前每隔一段时间都会起作用。

基本上,我正在创建一个 SQL 备份脚本,它将数据库备份到我们的网络共享,然后通过电子邮件发送给我是否成功。到目前为止,脚本的其余部分工作得很好。

标签: powershellpowershell-4.0

解决方案


在您的 If 和 Else 块中,不要创建变量$subject, 或$Mail,而是更新哈希表 , $MailParam。此外,您似乎缺少 Send- 中的 Attachment 变量MailMessage

if ($GetChildItem -eq $Null)
    {
    Write-Host "Backup Failed"
    $MailParam.Subject = "$env:COMPUTERNAME SQL Backup Failed"
    $MailParam.Body = "SQL Backup Failed on the server, please see the attached report for more details"
    $attachment = $reportfile, $debuglog
    Send-MailMessage @MailParam -usessl -BodyAsHtml -Attachments $attachment
    #Exit
    }

推荐阅读