powershell - 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 备份脚本,它将数据库备份到我们的网络共享,然后通过电子邮件发送给我是否成功。到目前为止,脚本的其余部分工作得很好。
解决方案
在您的 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
}
推荐阅读
- php - Laravel 得到一个错误未定义的偏移量:3
- javascript - “未捕获的 TypeError:无法处理绑定”与 KnockoutJS
- javascript - React Native Stripe 支付网关
- php - Laravel lavary 侧边栏菜单缓存
- php - 使用 UploadFileInterface 上传图片
- android - 将图像移动到布局的中心
- google-chrome-extension - Chrome 扩展 - 沙盒页面如何访问存储中的数据?
- mysql - 尝试在不存在的地方插入数据抛出:#1242 - 子查询返回超过 1 行
- delphi - Indy Header Last-Modified - 日期编码的参数无效
- react-native - React Native 地理位置权限回调