Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force Powershell to open a document as read-only and close without saving?

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.

enter image description here

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?

enter image description here

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();
}
like image 361
dwwilson66 Avatar asked Oct 30 '13 13:10

dwwilson66


1 Answers

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.

like image 101
crownedjitter Avatar answered Nov 10 '22 13:11

crownedjitter