Powershell – Run powershell.exe as a service, or help me find an alternate solution

powershellwindows-service

Summary: I need to run a Powershell script continuously in the background whether a user is logged on or not. This is on Server 2012.

I ran the following command:

sc.exe create "MyService" binPath="powershell.exe 'c:\myFolder\myScript.ps1'"

This command ran successfully. However, when I start the service, it immediately errors out with "The service did not respond in a timely fashion." I know it's against best practices to run Powershell as a service, but is it even possible?

The best advice I've gotten is to run this script as a Scheduled Task instead of a service. That would make sense, but my security staff has enabled the GPO option "Network access: Do not allow storage of passwords and credentials". This prevents Task manager from running tasks with the correct credentials when no user is logged in.

Why am I doing this? We have an old program that runs only in windowed mode (not as a service) and prints both stdout and stderr to the screen. That means that (a)a user has to be logged into this server 24 hours a day, and (b)there are no log files. If you're not staring at the screen when an error occurs, the error will scroll right past you. The executable starts in a new window, so redirection operators have no effect on it.

While we replace this program, I need it to (a)run at all times, even after user logoff or reboot, and (b)write stdout and stderr to a log file.

I solved the second issue with a Powershell simple Powershell script:

"Program started at $(get-date)" | Out-File c:\myFolder\CrapProgram.log -append
& "c:\myFolder\CrapProgram.exe" | Tee-Object c:\myFolder\CrapProgram.log

This starts the program in Powershell. Its output is directed both to the Powershell window and to the log file.

Now if I can get this script to run when no one is logged on…and get it to start at computer startup…and make it easy for my lower-level support team to stop and start it easily, I'll be in business.

That's why I'm trying to register Powershell as a service. If there's a better solution, let me know.

Best Answer

You could try running it as a scheduled task and set the user to run the task as 'NT Authority\System' . You don't have to enter a password for that account.