Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:631\pdf-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
like image 292
grom Avatar asked May 17 '10 02:05

grom


1 Answers

Turns out this is MUCH easier to do in VB.NET than in C# (which I never could figure out). But all you would need to do is create, say, a console application with a single routine. Here are the instructions:

Code

Imports word = Microsoft.Office.Interop.Word
Module Module1
    Sub Main()
        Dim args() As String = Environment.GetCommandLineArgs
        Dim path = args(1)
        Dim printer = args(2)
        Dim wordApp As word.Application = New word.Application
        wordApp.WordBasic.DisableAutoMacros(1)
        wordApp.Visible = False
        Dim doc As word.Document = wordApp.Documents.Open(path)
        wordApp.ActivePrinter = printer
        Dim background As Object = False
        doc.PrintOut(background)
        doc.Close(False)
        wordApp.WordBasic.DisableAutoMacros(0)
        wordApp.Quit()
    End Sub
End Module

Steps to recreate solution:

  1. Open VS2008 and create a new Console Application in VB.NET.
  2. Set a reference to Microsoft.Office.Interop.Word (version 11)
  3. Delete any code in Module1 and insert the code above.
  4. Save the project and name it "wordprinter". Build the project.
  5. Nav to the Release folder and grab the "wordprinter.exe" and put it anywhere you like. This will be your $wordprinterpath.
  6. Note the paths to your document and printer. This will be your $doc and $printer, respectively.
  7. Enter the following in PS:
        $wordprinterpath = "C:\\path\\wordprinter.exe"
        $doc ="""C:\\Users\\me\\Documents\\Your doc.doc"""
        $printer = "\\http://ptr-server:631\pdf-printer"
        Invoke-Expression "$wordprinterpath $doc $printer" | out-Null

You should be good to go after this. I haven't tested the printing part of this, so that may need some work, but disabling of the auto-macros and opening the doc works.

like image 174
Todd Main Avatar answered Sep 20 '22 22:09

Todd Main