Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell attachment.add正在使用defaut位置而不是set位置_Powershell - Fatal编程技术网

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

Powershell attachment.add正在使用defaut位置而不是set位置,powershell,Powershell,我对脚本和PowerShell非常陌生。正在编写一个脚本,该脚本将通过电子邮件发送它生成的日志文件。突然,我的附件add不再工作,而是给了我错误 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.M

我对脚本和PowerShell非常陌生。正在编写一个脚本,该脚本将通过电子邮件发送它生成的日志文件。突然,我的附件add不再工作,而是给了我错误

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
为什么此代码使用默认路径而不是当前设置的位置


我使用的是Powershell 2.0版。

因为您在
Get ChildItem
调用中添加了
-Name
,该调用返回的是文件名列表,而不是完整路径

删除
-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
}

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

除非我解释错误,$AttachmentList存储为字符串。运行$realfiles.fullname不会给我任何数据。这是检查值的正确语法,对吗?@rStyskel什么版本的powershell<代码>$realFiles.FullName仅适用于PowerShell 3+<代码>$realFiles[0]。FullName应显示任何版本的PowerShell上的第一个文件<代码>$AttachmentList不是字符串列表。您可以检查
$AttachmentList | Get Member
,查看每个成员的类型。TypeName:System.String。我正在使用版本2。0@rStyskel我的错误,我没有看到您将
-Name
添加到
Get ChildItem
。请参阅我的编辑。使用编辑中的代码,$AttachmentList为空。我感到双重困惑,因为昨天晚上我离开之前,原来的代码还在工作。
$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
}