0

I know how to already run an exe file, easy part. I also figured out how to run a command when powershell closes:

Register-EngineEvent PowerShell.Exiting –Action { 'Code' }

But I can't figure out how I would run a program with Powershell and then have it execute a command in Powershell when it closes, and then close Powershell itself.

$job = Start-Job { net start wuauserv }
Wait-Job $job
Receive-Job $job

Start-Process -FilePath "C:\Program Files (x86)\CpuCoreParking\CpuCoreParking3.exe" -Wait

Register-EngineEvent PowerShell.Exiting –Action {
$job = Start-Job { net stop wuauserv }
Wait-Job $job
Receive-Job $job
Start-Sleep -Seconds 2
}

This is my code so far, but it doesn't seem to stop the service on the end. Nothing happens, it just closes itself after I close the program. It does do something but ... not sure what.

3
  • 2
    the Start-Process cmdlet has a -Wait parameter that may give you all that you need for this. have you tried it? [grin] Commented Jan 22, 2019 at 23:59
  • Possible duplicate of this: stackoverflow.com/questions/31116756/… Commented Jan 23, 2019 at 4:52
  • Not a duplicate. I know how to run a command on exit. I was asking how to make the Powershell wait for a program run within it to close, before it closes itself automatically together with it. Commented Jan 24, 2019 at 0:31

1 Answer 1

0

Found out the problems:

First of all

Register-EngineEvent PowerShell.Exiting –Action {}

Makes the Powershell itself wait to be closed. So if it closes by the means of it finishing the execution of all commands, it will not run the command.

Second

Invoke-Expression -Command "cmd.exe /c net stop wuauserv"

This needs administrator privileges. So it's best you turn this into an exe files with admin privileges. That's the one method that comes to mind. Here is the finished code that functions as it should:

Invoke-Expression -Command "cmd.exe /c net start wuauserv"
Start-Sleep -Seconds 2
Register-EngineEvent PowerShell.Exiting –Action {
Invoke-Expression -Command "cmd.exe /c net stop wuauserv"
}
Start-Process -FilePath "C:\Program Files (x86)\CpuCoreParking\CpuCoreParking3.exe" -Wait
Invoke-Expression -Command "cmd.exe /c net stop wuauserv"
Start-Sleep -Seconds 2

Or you can replace the Invoke-Expression commands with

$job = Start-Job { net start/stop wuauserv }
Wait-Job $job
Receive-Job $job

Which I believe doesn't require admin privileges.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.