Send-MailMessage:无法验证参数' Subject'

时间:2017-05-05 13:32:33

标签: windows powershell

运行以下脚本时会出现此错误:

  

Send-MailMessage:无法验证参数' Subject'的参数。参数为null或空。提供非null或空的参数,然后再次尝试该命令。

电子邮件仍然成功发送,主题正确显示。

$dir = "C:\Users\user\Desktop\Lists\TodaysLists"
$SMTPServer = "192.168.1.111"
$Time = (Get-Date).ToString('MM/dd/yyyy hh:mm tt')

$japan = @{            
    Name = 'Japan'
    From = "me@me.com
    To   = "you@me.com"
    Cc   = "him@me.com"
}

$ireland = @{            
    Name = 'Ireland'
    From = "me@me.com
    To   = "you@me.com"
    Cc   = "him@me.com"
}

$Regions = @()
$Regions += New-Object PSObject -Property $japan
$Regions += New-Object PSObject -Property $ireland

foreach ($Region in $Regions) {
    $Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse
    $AttachmentName = $Attachment.BaseName
    $Subject = "$AttachmentName"
    $Body = "Please find attached the Report for $($Region.Name).

Produced @ $Time 

Regards,
John Doe
"
    Send-MailMessage -From $Region.From -To $Region.To -CC $Region.Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName
    $Attachment | Move-Item -Destination "C:\Users\user\Desktop\Lists\oldLists"
}

1 个答案:

答案 0 :(得分:2)

我的猜测是$Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse没有为一个或多个地区返回任何文件,因此$Subject最终为$null

您可以检查该状态,也许可以发出警告而不是尝试发送邮件,或者以其他方式解决错误(以及发送电子邮件但是有空白主题)将添加其他一些(保证)文本到$subject。 E.g:

$Subject = "$($Region.Name): $AttachmentName"

虽然我怀疑它会抱怨-Attachments为空。

要添加检查/投掷警告,您可以执行以下操作:

foreach ($Region in $Regions) {
    $Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse

    If ($Attachment) {

        $AttachmentName = $Attachment.BaseName
        $Subject = "$AttachmentName"
        $Body = "Please find attached the Report for $($Region.Name).

    Produced @ $Time 

    Regards,
    John Doe
    "
        Send-MailMessage -From $Region.From -To $Region.To -CC $Region.Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName
        $Attachment | Move-Item -Destination "C:\Users\user\Desktop\Lists\oldLists"
    } Else {
        Write-Warning "One or more files named $($Region.Name) were not found in $dir. Mail not sent."
    }
}