You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用Outlook添加附件报错:空值表达式调用方法

解决PowerShell调用Outlook添加附件时的Null引用错误

这个错误的根源其实是一个非常容易忽略的拼写小失误!

你在脚本里写的是:

$mail.Attachment.Add($attach)

但Outlook的COM对象中,邮件的附件集合属性是复数形式的Attachments(末尾多了个s)。因为你引用了不存在的Attachment属性,它的值是$null,所以调用Add()方法时就会抛出「无法对空值表达式调用方法」的错误。

修正后的代码片段

把Attachment改成Attachments即可:

for ($i=1;$i -lt $arr.Count - 1; $i++){
    if ($arr[$i] -eq "Something"){
        $attach="C:\testfile.txt"
        if (Test-Path -Path $attach -PathType Leaf) { # 更严谨的文件存在检查
            Write-Host "Adding attachment: $attach"
            $mail.Attachments.Add($attach) # 这里改成复数Attachments
        } else {
            Write-Warning "File $attach does not exist, skipping attachment"
        }
    }
    # 其他if判断逻辑...
}
$mail.Send()

补充说明

  1. 关于手动执行成功的原因:你提到在PowerShell命令行手动执行能成功,很大概率是你当时输入的是正确的Attachments(复数),而脚本里不小心写成了单数,导致不一致的结果。
  2. 可选的优化点:
    • 开头的Start-Process Outlook其实可以去掉,因为New-Object -ComObject Outlook.Application会自动启动Outlook进程(如果未运行的话),或者复用已有的进程实例。
    • 用Test-Path -Path $attach -PathType Leaf替代单纯的Test-Path,可以确保目标路径是一个文件而非文件夹,避免无效的附件添加尝试。

内容的提问来源于stack exchange,提问作者meh93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:31:48