Reputation: 113
I need to close the word/excel/powerpoint documents from taskbar with powershell script. Stop-process kills the process but it doesnt save the changes made. I need it to save and close the document. I am able to do it for word with following script:
$wd = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
$wd.Documents | % { $_.Close() }
Get-Process | ?{$_.ProcessName -eq "WINWORD"} | Stop-Process
When I do the same for excel and powerpoint I get error message and the changes are not saved. For Excel I have done as follows:
$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
$excel.ActiveWorkbook | % { $_.Close() }
Get-Process | ?{$_.ProcessName -eq "EXCEL"} | Stop-Process
For powerpoint:
$ppt= [Runtime.Interopservices.Marshal]::GetActiveObject('Powerpoint.Application')
$ppt.Presentations | % { $_.Close() }
Get-Process | ?{$_.ProcessName -eq "POWERPOINT"} | Stop-Process
Error displayed is:
+ $excel.ActiveWorkbook | % { $_.Close() }
+ ~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Close:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Upvotes: 2
Views: 5236
Reputation: 86
I don't remember where I got the base code for this but if anyone finds it please give the due credit. I modified it for your use case:
$isExcelOpen = Get-Process excel*
while ($isExcelOpen -ne $null) {
Get-Process excel* | ForEach-Object { $_.CloseMainWindow() | Out-Null }
sleep 5
If (($isExcelOpen = Get-Process excel*) -ne $null) {
Write-Host "Excel is Open.......Closing Excel"
$wshell = new-object -com wscript.shell
$wshell.AppActivate("Microsoft Excel")
$wshell.Sendkeys("%(S)")
$isExcelOpen = Get-Process excel*
}
}
You will need to change excel to word/powerpoint and possibly $wshell.Sendkeys to the proper letter
Upvotes: 0
Reputation: 21
This will prompt for save if needed and then close Excel: (Get-Process -Name "Excel").CloseMainWindow
Upvotes: 2
Reputation: 961
Try this code:
$excel.DisplayAlerts = $false; $excel.Workbooks | % { $_.Save(); $_.Close() }
Upvotes: 0