Send-MailMessage: Cannot validate argument on parameter 'Subject'

前端 未结 1 1788
无人共我
无人共我 2021-01-23 11:04

This error appears when running the script below:

Send-MailMessage : Cannot validate argument on parameter \'Subject\'. The argument is null or empty. Pro

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-23 11:58

    My guess would be that $Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse is not returning any files for one or more of the regions, so $Subject ends up being $null.

    You could either check for that state and perhaps throw a warning instead of attempting to send the mail, or another way to work around the error (and get an email sent but with a blank subject) would be to add some other (guaranteed) text to $subject. E.g:

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

    Although then I suspect it would complain about -Attachments being null.

    To add a check/throw warning, you could do the following:

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

    0 讨论(0)
提交回复
热议问题