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

使用PowerShell将PDF导入Word时遇类型转换错误求助

PowerShell调用Word COM插入PDF时类型转换错误的解决方法

错误原因分析

你遇到的Cannot convert the "False" value of type "bool" to type "Object"错误,根源是错误地为Word InsertFile方法的输入参数添加了[ref]包装。COM方法中只有输出/双向参数才需要用[ref]传递,而InsertFile的ConfirmConversions、Link、Attachment都是输入参数,直接传递布尔值即可,不需要额外包装。

解决步骤

  1. 移除不必要的[ref]包装:对InsertFile的布尔参数直接传$false,无需[ref];
  2. 限定处理PDF文件:避免循环中处理非PDF文件引发额外错误;
  3. 简化COM方法调用:SaveAs和Close方法的参数也无需[ref]包装,直接传递对应值即可;
  4. 增强COM对象清理:确保每次循环后释放$newDoc变量,避免内存泄漏。

修改后的完整代码

# Define paths
$folderPath = "my source folder"
$resultPath = "my destination folder"

# Create Word application COM object
$wordApp = New-Object -ComObject Word.Application
$wordApp.Visible = $false  # Set Word to run in the background

# Create FileSystemObject COM object
$fso = New-Object -ComObject Scripting.FileSystemObject

# Get the folder
$folder = $fso.GetFolder($folderPath)

# Loop through only PDF files in the folder
foreach ($file in $folder.Files | Where-Object { $_.Extension -eq ".pdf" }) {
    # Create a new Word document
    $newDoc = $wordApp.Documents.Add()

    # Insert PDF content into the new document (no [ref] needed for input parameters)
    try {
        $newDoc.Range().InsertFile($file.Path, $null, $false, $false, $false)
        
        # Add header text
        $newDoc.Content.InsertBefore("Processed document: " + $file.Name + "`n")

        # Define output path and save as DOCX
        $docName = [System.IO.Path]::Combine($resultPath, ($file.BaseName + "_processed.docx"))
        $newDoc.SaveAs($docName, 16)  # 16 = wdFormatXMLDocument
    }
    catch {
        Write-Error "Failed to process file $($file.Name): $_"
    }
    finally {
        # Close document and release COM object
        if ($newDoc) {
            $newDoc.Close($false)
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($newDoc) | Out-Null
            $newDoc = $null
        }
    }
}

# Cleanup Word COM object
$wordApp.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wordApp) | Out-Null
$wordApp = $null
$fso = $null

# Force garbage collection to release remaining COM objects
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

额外注意事项

  • 确保你的Word版本支持PDF导入(Word 2013及以上通常自带该功能,若缺失需安装Office的PDF组件);
  • 大体积PDF转换可能耗时较长,建议添加进度提示或分批处理;
  • 若仍报错,检查PDF文件是否损坏或受保护,这类文件无法通过Word直接插入转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:05:16