我正在使用 Word 通过打开文档并使用SaveAs()
.
我的代码:
# got that hint from http://stackoverflow.com/questions/36487507/troubles-using-powershell-and-word-saveas
[Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Word") | Out-Null
$Word = New-Object -ComObject "Word.Application"
$Word.Visible = $False
foreach ($transf_file in $doc_path) {
$transf_pdf_file = $transf_file -replace "`.docx?$", ".pdf"
$rel_path = Split-Path -Parent $transf_file
Copy-Item -Path "$src_pp_dir\$transf_file" -Destination "$dest_pp_dir\$rel_path" -Force
$word_doc = $Word.Documents.Open( "$dest_pp_dir\$transf_file" )
# Hess / Herlet workaround die nächste Zeile einkommentieren, die übernächste Zeile auskommentieren
#$word_doc.SaveAs( "$dest_pp_dir\$transf_pdf_file" ,17 )
$word_doc.SaveAs( [ref] [system.object] "$dest_pp_dir\$transf_pdf_file" ,[ref]17)
$word_doc.Close()
Remove-Item -Force -Path "$dest_pp_dir\$transf_file"
}
# this line avoids saving of normal.dot what is normally requested when another
# Word is open in parallel
# the rest is necessary to kill this word process (otherwise they sum up in the
# system and after a while it doesn't work anymore)
$Word.NormalTemplate.Saved = $true
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word) > $null
Remove-Variable Word
代码按预期在我的计算机上运行。在同事的计算机上:
$word_doc.SaveAs( [ref] [system.object] "$dest_pp_dir\$transf_pdf_file" ,[ref]17)
抛出错误:
参数:“1”不应该是 System.Management.Automation.PSReference。不要 使用[参考]。 在 D:\DMG\NX_Projekte\handle\PP-Encode.ps1:1015 char:7 + $word_doc.SaveAs( [ref] [system.object] "$dest_pp_dir\$transf_pdf_file" ,[ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : RefArgumentToNonRefParameterMsg
在他的机器上,之前的行(现在作为评论,没有[ref]
)工作正常。
我检查了什么:
- 我们使用相同版本的 PowerShell、Word、Word COM 对象、.NET Framework。
- 我浏览了这个网站上的提示,并特别改进了从 Word 的退出(确保所有 Word 进程都已完成——我的计算机上是什么情况)。
- 我在这里或其他地方都找不到这个特定问题的任何提示。