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
}
}
}
Close a DocumentClick the File tab. Click the Close.
Choose File > Exit to close your document and exit.
Close the current document: Press Ctrl + W to close the current document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With