Is there a way to force Powershell to open a document as read-only and close without saving?
For read only, try this:
$word.Documents.Open("$doc.Fullname", $false, $true)
For closing, try this:
$word.Documents.Close($false)
The MSDN links seem pretty clear about the order these parameters need to appear in and the above worked for me.
dwwilson66
Visual Communications Professional with a background in technology. In the thick of learning Java, PHP & MySQL to augment my web skills. I'm taking a shine to programming a lot more than I thought I would.
Updated on June 11, 2022Comments
-
dwwilson66 about 2 years
I have a script that parses data from Word documents. I arrived to the office this morning to realize that the script hadn't completed, hanging on a "File In Use" dialog box. I found a reference to the
$true
parameter -- open Read-Only -- on MSDN, but I still get the dialog box.And of course, one thing leading to another, now I also get the dialog box asking if I want to save changes before I can open the NEXT document, which can't be accessed because of an open dialog box. Sigh. How can I open a document, scan it for my data (the hyperlinks) and then close the document without saving?
Code appears here. I have not included the step where I write
$hyperlinks
to a file; I'm just concentrating on getting the file-read-close part working.$global:word = new-object -ComObject Word.Application $word.Visible = $False $backupPath = "\\Path\to\files\" # Backup data path $srcfiles = Get-ChildItem $backupPath -filter "*.doc" # foreach ($doc in $srcfiles) { $word.documents.Open($doc.Fullname,$true); $links = @($doc2.Hyperlinks); $links $word.Quit(); }
-
mjolinor over 10 yearsI don't mess with COM much, but if the Microsoft Word Viewer is a COM application, it seems like that migh be a better choice for what it is you're trying to accomplish.
-
-
webwurst about 9 yearsFor closing I had to use this:
$document.Close([ref] [Microsoft.Office.Interop.Word.WdSaveOptions]::wdDoNotSaveChanges)
. See msdn Documents.Close.