How to write Powershell script to open and close a program?

Viewed 49

I'm trying to write a PowerShell script that closes a program that is running, open it again, and close its window (without killing the process).

So far, I've tried the following code:

Stop-Process -Name "ACMON" 
Start-Process -FilePath "C:\Program Files\WindowsApps\B9ECED6F.Splendid_1.0.15.0_x64__qmba6cd70vzyy\ACMON.exe"
exit

The script above works as I expected. It closes the running program and opens it again. But the program's window pops up and I have to manually close it every time I run the script (by clicking the X top right corner or using ALT-F4).

What I want now is to close the program, open it again, and close the window. If I hit ALT-F4, the window closes, and the process keeps running.

I've searched about keystroking and tried this:

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}')

And this:

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}')

However, both ways don't seem to work, at least not the last part of it. It closes the app, opens it again, but doesn't close its window when it pops up.

Sorry guys, I'm very newbie in PowerShell and programming in general. That's why I'm struggling here. If anybody could help me, I'd be glad.

1 Answers
  • Use Start-Process with the -PassThru switch in order to obtain a System.Diagnostics.Process instance describing the newly launched process.

  • In a polling loop, wait until this process-info object's .MainWindowHandle has a non-zero value, indicating that the launched process has created its main window.

  • Then send the main window a close-request message via the .CloseMainWindow() method, which is the equivalent of trying to close the window interactively.

The following code demonstrates this, using Notepad as the target application:

$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()
Related