我取得了一些进步,并且坚持使用附件。下面的脚本现在发送一封电子邮件,但没有附件
$sub = "APERAK/INVRPT Report "
$to="Chandan.Talasila@XXXXXXXX.com"
$folder = "C:\script\APERAK"
$files = Get-ChildItem "C:\script\APERAK"
$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”自变量调用“添加”的异常:“值不能为null。 参数名称:项目“ 在C:\ GentranScripts \ APERAK_REPORT_EMAIL1.ps1:22 char:21 + $ MSG.attachments.add <<<<($ attachment) + CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException
答案 0 :(得分:2)
问题在于Get-Childitem
将返回两种类型的对象。如果只有一个文件,则$files = Get-ChildItem "C:\Reports\APERAK"
将包含一个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:\Reports\APERAK")