powershell - Attachment.add 使用默认位置而不是设置位置

标签 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 版。

最佳答案

因为您将 -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/

相关文章:

json - Powershell无需迭代即可直接引用JSON对象

powershell - 无法更改 powershell 版本

powershell - 升级后 SqlPackage.exe 命令抛出错误

datetime - 我可以控制 cmdlet 显示的日期时间格式吗?

bash - 如何在错误时停止Powershell脚本?

powershell - 为什么我需要将 'parametersetname' 与 PowerShell 开关一起使用?

image-processing - 无法加载文件或程序集 'AForge, Version=2.2.4.0, ... '

c# - 返回证书列表选择 azure VPN

forms - 如何使用 pwsh 中的新 param -form 登录网站

c# - 执行 C# 交互式 powershell 脚本