PowerShell Script to Run Before Certain Service
Run a PowerShell script at server startup before a certain service runs.
October 8, 2014
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:
Launch gpedit.msc.
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.)
Double-click Shutdown in the details window and select the PowerShell scripts tab.
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
You May Also Like