我通过打开文档并使用SaveAs()
编写文档,使用Word将docx从PowerShell转换为PDF。
我的代码:
# 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)
抛出错误:
Argument: '1' should not be a System.Management.Automation.PSReference. Do not use [ref]. At 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]
),工作正常。
我检查了什么: