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

求可用PowerShell脚本:通过Microsoft Word将HTML转换为RTF

使用PowerShell借助Microsoft Word将HTML转换为RTF的可行脚本

下面是经过验证的脚本,解决了公开代码常见的进程残留、路径错误、格式识别失效等问题:

param(
    [Parameter(Mandatory=$true)]
    [string]$HtmlPath,
    [Parameter(Mandatory=$true)]
    [string]$OutputRtfPath
)

# 统一转换为绝对路径,规避相对路径解析问题
$HtmlPath = Resolve-Path -Path $HtmlPath
$outputDir = Split-Path $OutputRtfPath -Parent
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir | Out-Null
}
$OutputRtfPath = Join-Path $outputDir (Split-Path $OutputRtfPath -Leaf)

$wordApp = $null
$targetDoc = $null

try {
    # 初始化Word应用实例,后台运行无界面
    $wordApp = New-Object -ComObject Word.Application
    $wordApp.Visible = $false
    $wordApp.DisplayAlerts = 0 # 禁用所有弹窗提示

    # 以HTML格式打开文档(10对应wdOpenFormatHTML常量)
    $targetDoc = $wordApp.Documents.Open(
        $HtmlPath,
        $false,  # 不修改原文档
        $true,   # 以只读模式打开
        $false,  # 不添加到最近文件列表
        "", "", $false, "", "", 10
    )

    # 保存为RTF格式(6对应wdFormatRTF常量)
    $targetDoc.SaveAs2($OutputRtfPath, 6)

    Write-Host "转换成功:$OutputRtfPath"
}
catch {
    Write-Error "转换失败:$($_.Exception.Message)"
}
finally {
    # 强制清理资源,避免Word进程残留
    if ($targetDoc) {
        $targetDoc.Close([Microsoft.Office.Interop.Word.WdSaveOptions]::wdDoNotSaveChanges)
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($targetDoc) | Out-Null
    }
    if ($wordApp) {
        $wordApp.Quit()
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($wordApp) | Out-Null
    }
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

关键修复点(解决公开脚本的常见问题)

  • 强制清理Word进程:通过ReleaseComObject和垃圾回收,彻底关闭后台残留的Word.exe进程
  • 直接使用格式数值:避免PowerShell无法识别Word枚举常量的问题,直接用官方定义的数值(10=HTML格式,6=RTF格式)
  • 路径预处理:自动创建输出目录、转换为绝对路径,解决相对路径找不到文件的问题
  • 无干扰运行:禁用Word界面和弹窗,确保脚本在后台静默执行

使用方法

  1. 将脚本保存为Convert-HtmlToRtf.ps1
  2. 打开PowerShell,运行:
.\Convert-HtmlToRtf.ps1 -HtmlPath "你的HTML文件绝对路径" -OutputRtfPath "输出RTF文件的绝对路径"

前置要求

  • 必须安装Microsoft Word(支持2013及以上版本)
  • 运行PowerShell的用户需有足够权限访问输入/输出路径

内容的提问来源于stack exchange,提问作者Filip Konvička

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:06:16