PowerShell Script to Run Before Certain Service

Run a PowerShell script at server startup before a certain service runs.

John Savill

October 8, 2014

1 Min Read
PowerShell command prompt

Q: I need a PowerShell script to run every time my server starts, but I need it to start before a certain service; how can I do this?

A: I recently had someone ask this question because they wanted to run some PowerShell code to check and set permissions before the SQL Server service started. A typical way to run something when the machine starts up is to use the machine's policy and configure a startup script; for example:

  1. Launch gpedit.msc.

  2. Navigate to Computer Configuration, Windows Settings, Scripts (Startup/Shutdown). (If you want to configure this for several computers, you can use Group Policy to configure and apply at a site, domain, or OU level.)

  3. Double-click Shutdown in the details window and select the PowerShell scripts tab.

  4. Add the PowerShell script you want to execute and click OK.

The challenge is that this script execution is performed by the Group Policy Engine, and the exact time at which the startup script will execute is non-deterministic, meaning there's no way to ensure it will always run before a service starts. To solve this problem, I recommend the following:

  • Using Services.msc, set the service that needs to start after the script runs to a startup type of Manual (right-click the service, select Properties, and on the General tab change the Startup type to Manual).

  • In your script that gets called via policy, perform a start of the service at the end of the script. You'll need to check whether other services that depend on the service you're starting here need to be started/set to manual.

You're now running a script and then starting the service, thus ensuring that the script runs first.

About the Author(s)

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like