Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

ms word - How to open document that contains AutoOpen macro with PowerShell?

My current PowerShell script:

$document = "C:\test.doc"
$word = new-object -comobject word.application
$word.Visible = $false
$word.DisplayAlerts = "wdAlertsNone"
$word.AutomationSecurity = "msoAutomationSecurityForceDisable"
$doc = $word.Documents.Open($document)
$word.ActivePrinter = "\http://ptr-server:631pdf-printer"
$background = $false
$doc.PrintOut([ref]$background)
$doc.close([ref]$false)
$word.quit()

But it results in an alert box The macros in this project are disabled. Please refer to the online help or documentation of the host application to determine how to enable macros.

How can I open the document without it running the AutoOpen macro or displaying any sort of dialog prompt?

Environment Details:

  • Word 2003 SP3
  • Windows Server 2003 R2 - Standard Edition - Service Pack 2
  • Powershell Version 1.0
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue you're experencing is documented at KB-886633 (Nevermind that it is talking about Office for Mac - the same applies on PCs):

Additionally, if a macro tries to open a file that contains a macro, the attempt will fail if both of the following conditions are true:

  • The Application.AutomationSecurity property option is set to
    msoAutomationSecurityForceDisable.
  • The attempt to open the file is made through an Office API macro. This includes macros that are written in VBA, XLM in Excel, and WordBasic in Word.

Both bullet points apply to your script.

The only way I know to get around it is to go old-school - with WordBasic - to disable all Auto Macros (AutoOpen, AutoExec, etc.). Insert $word.WordBasic.DisableAutoMacros right before $word.AutomationSecurity = "msoAutomationSecurityForceDisable". Note that there is no equivalant to this routine in VBA.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...