Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Quit or Close (not Kill) Word document (process)?

In our company we are using Windows application to generate Word (2010) documents. Sometimes the document is not properly closed, so another application (yes, they still call it development:) kill word process which is running more than 1 minute.

These killed processes are stored in MS Word's "Document Recovery". These Document recovery is not possible to turn off in Word 2010 (Options/"Save Autorecover info.." does'n solve the problem). When these "Document Recovery" is full of documents (tens or hundreds), the application stops to generate documents and we need to manually clear the front.

I was able to write this script to identify and kill the processes which are running more than 10 seconds, but is there a way how to close it properly (without killing it)?

I found this tutorial to create and quit word document with powershell, but how to connect specific word process with these MS Office method to close document?

Powershell and Word tutorial

$timer = 10
$date = Get-Date

if (Get-Process winword*) {
    Get-Process winword | foreach { 
        if ((($date - $_.StartTime).Seconds) -gt $timer) {
            $procID = $_.id
            Write-Host -ForegroundColor Magenta "Process $procID is running longer than $timer seconds."
            Write-Host -ForegroundColor Green "Killing process $procID.."
            Stop-Process $procID
        }
    }
}
like image 390
culter Avatar asked Aug 12 '13 15:08

culter


People also ask

How do you close a word processing document?

Close a DocumentClick the File tab. Click the Close.

How do you close a document?

Choose File > Exit to close your document and exit.

What is the command for closing a document?

Close the current document: Press Ctrl + W to close the current document.


1 Answers

You need to attach to the running Word instance as described here, and then close the document:

$wd = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
$wd.Documents | ? { $_.Name -eq 'some.docx' } | % {
  $_.Saved = $true
  $_.Close()
}

This must be run in the context of the user who started the application, and it will only attach to the instance started first (usually there's only one instance running anyway). You'd need to quit that instance first before you can attach to the instance started second.

like image 96
Ansgar Wiechers Avatar answered Sep 30 '22 15:09

Ansgar Wiechers