attachment.add正在使用defaut位置而不是设置位置

时间:2015-12-17 15:20:50

标签: powershell

我是脚本和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版。

2 个答案:

答案 0 :(得分:1)

因为您在-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
}

答案 1 :(得分:1)

我已经确定了这个问题。使用Set-Location将更改工作位置,但工作目录保持不变。我需要将[Environment]::CurrentDirectory更改为我从中提取文件的目录。

相关问题