![](/img/trans.png)
[英]how to check if a .html file is open, if yes, close it using windows PowerShell script
[英]How to write Powershell script to open and close a program?
我正在嘗試編寫一個 PowerShell 腳本來關閉正在運行的程序,再次打開它,然后關閉它的窗口(不終止進程)。
到目前為止,我已經嘗試了以下代碼:
Stop-Process -Name "ACMON"
Start-Process -FilePath "C:\Program Files\WindowsApps\B9ECED6F.Splendid_1.0.15.0_x64__qmba6cd70vzyy\ACMON.exe"
exit
上面的腳本按我的預期工作。 它關閉正在運行的程序並再次打開它。 但是程序的窗口會彈出,每次運行腳本時我都必須手動關閉它(通過單擊右上角的 X 或使用 ALT-F4)。
我現在想要的是關閉程序,再次打開它,然后關閉窗口。 如果我按 ALT-F4,窗口會關閉,並且進程會繼續運行。
我搜索了按鍵並嘗試了這個:
Stop-Process -Name "ACMON"
Start-Process -FilePath "C:\Program Files\WindowsApps\B9ECED6F.Splendid_1.0.15.0_x64__qmba6cd70vzyy\ACMON.exe"
exit
$wsh = New-Object -ComObject Wscript.Shell
$wsh.AppActivate("ACVT.exe")
Start-Sleep 1
$wsh.SendKeys('%{F4}')
和這個:
Stop-Process -Name "ACMON"
Start-Process -FilePath "C:\Program Files\WindowsApps\B9ECED6F.Splendid_1.0.15.0_x64__qmba6cd70vzyy\ACMON.exe"
exit
$wsh = New-Object -ComObject Wsscript.Shell
$wsh.AppActivate("ACVT.exe")
Start-Sleep -Miliseconds 1000
[System.Windows.Forms.SendKeys]::SendWait('%{F4}')
然而,這兩種方法似乎都不起作用,至少不是最后一部分。 它關閉應用程序,再次打開它,但在彈出時不會關閉它的窗口。
抱歉,我是 PowerShell 和一般編程方面的新手。 這就是為什么我在這里掙扎。 如果有人可以幫助我,我會很高興。
使用帶有-PassThru
開關的Start-Process
以獲得描述新啟動進程的System.Diagnostics.Process
實例。
在輪詢循環中,等到這個進程信息對象的.MainWindowHandle
有一個非零值,表明啟動的進程已經創建了它的主窗口。
然后通過.CloseMainWindow()
方法向主窗口發送關閉請求消息,這相當於嘗試以交互方式關閉窗口。
以下代碼演示了這一點,使用記事本作為目標應用程序:
$exe = 'Notepad.exe'
Write-Verbose -Verbose "Launching '$exe'..."
$ps = Start-Process $exe -PassThru
Write-Verbose -Verbose 'Waiting for the launched process'' main window to appear...'
do {
Write-Host . -NoNewline
Start-Sleep -Milliseconds 300
} while (0 -eq $ps.MainWindowHandle)
Write-Host
Read-Host 'Main window found; press Enter to send a close request message'
Write-Verbose -Verbose 'Sending close message; the return value indicates whether the message could be posted.'
$ps.CloseMainWindow()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.