在PowerShell的Word对象上使用SaveAs失败并显示[ref]参数错误

时间:2016-10-04 12:17:43

标签: powershell ms-word com-object

我通过打开文档并使用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]),工作正常。

我检查了什么:

  • 我们使用相同版本的PowerShell,Word,Word COM对象,.NET Framework。
  • 我扫描了这个网站上的提示并特别改进了退出Word(确保所有Word流程都已完成 - 我的计算机上的情况如何)。
  • 我无法在此处或其他地方找到任何有关此特定问题的提示。

0 个答案:

没有答案