Powershell-提供不包含任何空值的集合
我有一个Powershell脚本,它运行SQL Server查询,将其导出到Excel文件,然后将Excel文件作为附件发送电子邮件。我使用的Excel exporter来自以下位置: 以下是脚本:Powershell-提供不包含任何空值的集合,powershell,Powershell,我有一个Powershell脚本,它运行SQL Server查询,将其导出到Excel文件,然后将Excel文件作为附件发送电子邮件。我使用的Excel exporter来自以下位置: 以下是脚本: ##--Variables Start $FileName = "C:\Users\user\Documents\Report.xlsx"; $ConnectionString = "OurConnectionString" $secpasswd = "emailpassword" $cred =
##--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
变量中存在所谓的空值,因此发送邮件失败-我收到以下错误:
发送邮件消息:无法验证参数“附件”上的参数。参数为null、空或参数集合的元素包含null值。提供一个集合
不包含任何空值,然后重试该命令。
在C:\Users\Desktop\Untitled1.ps1:58 char:18
+发送MailMessage@mailparam-usesl
+ ~~~~~~~~~~
+CategoryInfo:InvalidData:(:)[Send MailMessage],参数BindingValidationException
+FullyQualifiedErrorId:ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage
我的语法有什么问题,$Attachment
变量为空
我有另一个脚本,它几乎与此相同,但它没有使用$xlsFile=@($datasetable | Export Excel$FileName-AutoSize)
进行Excel导出,而是使用了一个较旧的PowerShell ComObject和更多的代码来完成Excel部分-另一个脚本也以:
$Attachment = $xlsFile
Send-MailMessage @mailparam -UseSsl
然而,当运行带有附件的电子邮件时,它工作得很好。我终于注意到,在将任何值分配给$attachment之前,您的splat已经定义好了。[blush]这意味着splat在该参数中没有任何内容
fix=将splat移动到标准位置-就在使用它的调用之前-因此在它使用的所有$Vars赋值之后。[grin]在命令
$xlsFile=@($datasetable | Export Excel$FileName-AutoSize)
$xlsFile为空,因为Export Excel不返回任何内容。使用$Attachment=$FileName
@LotPings谢谢你的建议。我尝试使用$FileName
,但收到了另一个错误,FileNotFound
异常找不到文件“C:\”。
该路径是$FileName
变量的值。在脚本中,未定义$FileName以上的值。引用帮助参数-附件指定要附加到电子邮件的文件的路径和文件名。您可以使用此参数或管道路径和文件名来发送邮件消息
@Stpete111-不,我只是简单地介绍了诊断依据。//我刚刚注意到一些。。。您在$Attachment
变量包含任何内容之前定义splat。。。[grin]将splat定义移动到标准位置-就在使用它的调用之前,然后查看它是否正常工作。@Stpete111-完成!如果你有任何改进的建议,请告诉我。[咧嘴笑]