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

如何用PowerShell提取.eml文件中的附件?

提取EML文件中的附件

你可以利用CDO Attachment对象的SaveToFile方法实现附件保存,以下是补充完整的代码:

# EML文件路径
$emlFn = "thedirectory\file.eml"
# 附件保存目录,可自行修改
$saveDir = ".\ExtractedAttachments"

# 创建保存目录(如果不存在)
if (-not (Test-Path -Path $saveDir)) {
    New-Item -ItemType Directory -Path $saveDir | Out-Null
}

$adoDbStream = New-Object -ComObject ADODB.Stream
$adoDbStream.Open()
$adoDbStream.LoadFromFile($emlFn)

$cdoMessage = New-Object -ComObject CDO.Message
$cdoMessage.DataSource.OpenObject($adoDbStream, "_Stream")

foreach ($attachment in $cdoMessage.Attachments) {
    $fileName = $attachment.FileName
    Write-Output "正在保存附件: $fileName"
    
    # 拼接完整保存路径
    $savePath = Join-Path -Path $saveDir -ChildPath $fileName
    
    # 保存附件到本地
    $attachment.SaveToFile($savePath)
}

# 清理资源
$adoDbStream.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($cdoMessage) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($adoDbStream) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

关键说明:

  • $saveDir:指定附件要保存到的本地目录,可根据需求修改路径
  • Test-Path + New-Item:确保保存目录存在,避免保存时因目录不存在报错
  • Join-Path:安全拼接保存路径,规避文件名含特殊字符或路径格式问题
  • SaveToFile:CDO Attachment对象内置方法,直接将附件内容写入指定路径
  • 资源清理部分:释放COM对象并触发垃圾回收,避免PowerShell进程残留未释放的COM资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:44:54