【问题标题】:Send-MailMessage: Cannot validate argument on parameter 'Subject'Send-MailMessage:无法验证参数“主题”上的参数
【发布时间】:2017-10-04 00:25:37
【问题描述】:

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

Send-MailMessage:无法验证参数“主题”的参数。参数为 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"
}

【问题讨论】:

  • 可能不相关,但您的哈希表的 From 值缺少右双引号。
  • 代码尝试发送两封电子邮件,您说“电子邮件发送正确” - 简单的答案是一封正确发送,一封失败...?
  • 可能值得将 -Verbose 添加到 Send-MailMessage 以帮助您查找故障。

标签: windows powershell


【解决方案1】:

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

您可以检查该状态并可能发出警告而不是尝试发送邮件,或者解决错误的另一种方法(并发送一封电子邮件但主题为空白)将添加一些其他(保证)发短信给$subject。例如:

$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."
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2023-02-23
    • 2019-06-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多