【发布时间】:2019-03-30 22:18:40
【问题描述】:
我有一个 Powershell 脚本,它运行 SQL Server 查询,将其导出到 Excel 文件,然后应该将该 Excel 文件作为附件通过电子邮件发送。我使用的 Excel 导出器来自这里:https://github.com/dfinke/ImportExcel
这是脚本:
##--Variables Start
$FileName = "C:\Users\user\Documents\Report.xlsx";
$ConnectionString = "OurConnectionString"
$secpasswd = "emailpassword"
$cred = New-Object System.Management.Automation.PSCredential ("emailaddress", $secpasswd)
$SmtpCred = $cred
$ToAddress = 'to@contoso.com'
$FromAddress = 'from@contoso.com'
$SmtpServer = 'smtp.server.com'
$SmtpPort = '587'
$Subject = 'Report'
$Body = "Here is your report"
$mailparam = @{
To = $ToAddress
From = $FromAddress
Subject = $Subject
Body = $Body
Attachments = $Attachment
SmtpServer = $SmtpServer
Port = $SmtpPort
Credential = $SmtpCred
}
$SqlQuery = @"
SELECT TOP 10 * FROM dbo.table
"@;
##--Variables End
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = $ConnectionString;
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $SqlQuery;
$SqlCmd.Connection = $SqlConnection;
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
$xlsFile = @($DataSetTable | Export-Excel $FileName -AutoSize)
$SqlConnection.Close()
$Attachment = $xlsFile
Send-MailMessage @mailparam -UseSsl
运行上述脚本后,Excel 文件正确导出,但由于$Attachment 变量中存在所谓的空值,发送邮件失败 - 我收到以下错误:
Send-MailMessage:无法验证参数“附件”上的参数。参数为 null、空,或参数集合的元素包含 null 值。提供一个集合 不包含任何空值,然后重试该命令。 在 C:\Users\Desktop\Untitled1.ps1:58 char:18 + 发送邮件消息@mailparam -UseSsl + ~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage
我的语法有什么问题导致$Attachment 变量为空?
我有另一个几乎与此相同的脚本,但它没有使用 $xlsFile = @($DataSetTable | Export-Excel $FileName -AutoSize) 进行 Excel 导出,而是使用带有更多代码的旧 PowerShell ComObject 来执行 Excel 部分 - 其他脚本也以:
$Attachment = $xlsFile
Send-MailMessage @mailparam -UseSsl
但带有附件的电子邮件在运行时可以正常工作。
【问题讨论】:
-
在命令
$xlsFile = @($DataSetTable | Export-Excel $FileName -AutoSize)$xlsfile 是空的,因为 Export-Excel 不返回任何内容。使用$Attachment = $FileName -
@LotPings 感谢您的建议。我尝试使用
$FileName,但收到不同的错误,FileNotFound异常。Could not find file 'C:\<the path to the file>'.该路径是$FileName变量的值。 -
在你上面的脚本中 $filename 没有定义。引用帮助
Parameter -Attachments <String[]> Specifies the path and file names of files to be attached to the email message. You can use this parameter or pipe the paths and file names to Send-MailMessage -
@Stpete111 - 不,我只是涵盖了诊断基础。///// 我刚刚注意到一些事情......你在
$Attachment变量有任何内容之前定义了splat它... [grin] 将 splat 定义移动到 标准位置 - 就在使用它的调用之前,看看它是否正常工作。 -
@Stpete111 - 完成!如果您对改进它有任何建议,请告诉我。 [咧嘴]
标签: powershell