Microsoft Word Interop:SaveAs挂起了一些错误的参数类型 [英] Microsoft Word Interop: SaveAs hangs for some misterious argument types
问题描述
当尝试简化从Word转换为PDF的PowerShell脚本时,我发现了以下令人奇怪的场景。以下是概念验证互动会议的笔录:
When trying to simplify a PowerShell script that converts from Word to PDF, I found out the following weird scenario that blows my mind. Here's the transcript from a proof of concept interactive session:
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
PS C:\Users\Frag> Add-Type -AssemblyName Microsoft.Office.Interop.Word
PS C:\Users\Frag> $word = New-Object -ComObject Word.Application
PS C:\Users\Frag> $i = Get-Item ".\document.docx"
PS C:\Users\Frag> $i.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True FileInfo System.IO.FileSystemInfo
PS C:\Users\Frag> $i.FullName
C:\Users\Frag\document.docx
PS C:\Users\Frag> $doc = $word.Documents.Open($i.FullName)
PS C:\Users\Frag> $doc.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False DocumentClass System.__ComObject
PS C:\Users\Frag> $good = $i.FullName.Remove($i.FullName.Length - $i.Extension.Length) + ".pdf"
PS C:\Users\Frag> $bad = Join-Path $i.DirectoryName ($i.BaseName + ".pdf")
PS C:\Users\Frag> $good
C:\Users\Frag\document.pdf
PS C:\Users\Frag> $bad
C:\Users\Frag\document.pdf
PS C:\Users\Frag> $good -eq $bad
True
PS C:\Users\Frag> $good.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS C:\Users\Frag> $bad.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS C:\Users\Frag> Remove-Item -LiteralPath $good -Force -ErrorAction SilentlyContinue
PS C:\Users\Frag> $doc.SaveAs($good, [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatPDF)
PS C:\Users\Frag> dir $good
Directory: C:\Users\Frag
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 11/03/2017 22:50 174616 document.pdf
PS C:\Users\Frag> Remove-Item -LiteralPath $good -Force
PS C:\Users\Frag> $doc.SaveAs($bad, [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatPDF)
最后一个命令挂起,必须关闭外壳窗口以及从任务管理器中杀死的不可见Word实例。
The last command hangs, and the shell window has to be closed as well as the invisible Word instance killed from the task manager.
从外观上看, $好
和 $坏
似乎是不同的字符串类型。有人知道这是怎么回事吗?
By the looks of it, $good
and $bad
appear to be of different string types. Does anyone know what is going on here?
我设法通过添加一个显式来解决此问题演员:
I managed to fix the issue by adding an explicit cast:
PS C:\Users\Frag> [string]$bad = Join-Path $i.DirectoryName ($i.BaseName + ".pdf")
问题已经解决,但我还是非常感谢您的解释或指导。
So the issue is gone, but I'd still very much appreciate an explanation or a pointer.
推荐答案
$saveFormat = [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatDocumentDefault
$doc.saveas([ref][system.object]$wordFile, [ref]$saveFormat)
为我工作...
这篇关于Microsoft Word Interop:SaveAs挂起了一些错误的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!