我对脚本编写和 PowerShell 非常陌生。一直在开发一个脚本,该脚本部分将通过电子邮件发送其生成的日志文件。突然我的附件添加不再工作,而是给我错误
Cannot convert argument "0", with value: "test_2015-12-16.log", for "Add" to type "System.Net.Mail.Attachment": "Cannot convert value "test_2015-12-16.log" to type "System.Net.Mail.Attachment". Error: "Could not find file 'C:\
Windows\system32\test_2015-12-16.log'.""
At line:8 char:23
+ $email.attachments.add <<<< ($realFiles[$i])
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
在我之前的脚本中set-location $emailLogTarget
,我遇到问题的代码是:
$AttachmentList = get-childitem -path $EmailLogTarget -include "*.log" -name
$AttachmentList
$realFiles = $AttachmentList | ? {Test-Path -Path $_}
for ($i=0; $i -lt $realFiles.length; $i++)
{
new-object Net.Mail.Attachment($realFiles[$i])
$email.attachments.add($realFiles[$i])
}
为什么此代码使用默认路径而不是当前设置的位置?
我使用的是 Powershell 2.0 版。
最佳答案
因为您将 -Name
添加到 Get-ChildItem
调用中,并且返回了文件名列表而不是完整路径。
删除 -Name
,然后使用我下面的建议。
因为 $attachmentList
不是字符串形式的文件列表,它是 [System.IO.FileInfo]
对象的列表,当嵌入到字符串,或者在本例中转换为字符串,因为每个字符串都被传递到附件对象的构造函数中,它们仅显示为文件名,而不是完整路径。
相反,您可以只使用 .FullName
属性:
$AttachmentList = get-childitem -path $EmailLogTarget -include "*.log"
for ($i=0; $i -lt $realFiles.length; $i++)
{
new-object Net.Mail.Attachment($realFiles[$i].FullName)
$email.attachments.add($realFiles[$i]) # I imagine you don't want the full name here
}
关于powershell - Attachment.add 使用默认位置而不是设置位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34338092/