我已经取得了一些进展,并坚持使用附件。下面的脚本现在发送一封电子邮件,但没有附件
$sub = "APERAK/INVRPT Report "
$to="Chandan.Talasila@XXXXXXXX.com"
$folder = "C:scriptAPERAK"
$files = Get-ChildItem "C:scriptAPERAK"
$tstmp = Get-Date -UFormat "%H%M"
$dstamp = Get-Date -UFormat "%Y%m%d"
$from="Reports@XXXXXXXX.com"
$smtpserver = "mail.XXXXXXXX.com"
for ($i=0; $i -lt $files.Count; $i++) {
$subject= $sub + $dstamp #+ " " +$tstmp
$filename = $files[$i].FullName
$abpath = $folder + $files[$i].FullName
$attachment = new-object Net.Mail.Attachment($abpath)
$body= Get-Content $filename
$SMTP = new-object Net.Mail.SmtpClient($smtpserver)
$MSG = new-object Net.Mail.MailMessage($from, $to, $subject, $body)
$MSG.attachments.add($attachment)
$SMTP.send($msg)
}
使用"1"个参数调用"Add"时发生异常:"值不能为null。参数名称:item"在C:\GentranScripts\APERAK_REPORT_EMAIL1.ps1:22 char:21+$MSG.附件.add<lt<lt;(附件$(+CategoryInfo:未指定:(:([],MethodInvocationException+FullyQualifiedErrorId:DotNetMethodException
问题是Get-Childitem
将返回两种类型的对象。如果只有一个文件,则$files = Get-ChildItem "C:ReportsAPERAK"
将包含一个FileInfo
。如果还有更多,它将包含一个FileInfo对象数组。让我们来看一个示例案例:
md foo
cd foo
set-content -Path "foo.txt" -Value ""
$files = gci
$files.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True FileInfo System.IO.FileSystemInfo
set-content -Path "foo2.txt" -Value ""
$files2 = gci
$files2.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
对于解决方案,将gci
结果封装到一个数组中。像这样,
$files = @(Get-ChildItem "C:ReportsAPERAK")