简体   繁体   English

如何使用powershell保存和停止MS Office进程?

[英]How to save and stop MS Office process with powershell?

I need to close the word/excel/powerpoint documents from taskbar with powershell script.我需要使用 powershell 脚本从任务栏中关闭 word/excel/powerpoint 文档。 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:我可以使用以下脚本为 word 做这件事:

$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.当我对 excel 和 powerpoint 执行相同操作时,我收到错误消息并且未保存更改。 For Excel I have done as follows:对于 Excel 我做了如下:

$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
$excel.ActiveWorkbook | % { $_.Close() }
Get-Process | ?{$_.ProcessName -eq "EXCEL"} | Stop-Process

For powerpoint:对于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

如果需要,这将提示保存,然后关闭 Excel:(Get-Process -Name "Excel").CloseMainWindow

试试这个代码:

$excel.DisplayAlerts = $false; $excel.Workbooks | % { $_.Save(); $_.Close() }

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您需要将 excel 更改为 word/powerpoint 并可能将 $wshell.Sendkeys 更改为正确的字母

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM