Can you write Windows services in Powershell

荒凉一梦 提交于 2019-11-29 12:02:18

If you absolutly want to execute your PowerShell code into a service, I think you can write a C# service wrapper for PowerShell code.

You found examples of how to create a service with C#, and it's simple to call Powershell from C#. So I'am surprised that as small SrvAny oriented PowerShell does not exists yet.

My advice here, you better rewrite your code in C# as a service.

There are a few items at issue here:

  • Are you sure that you really need a service? I agree with the comments about using the scheduler for running periodic tasks. The scheduler can start tasks as Administrator.
  • Services call a special set of APIs to communicate with the Service Control Manager, so an ordinary program can't be used directly.
  • The Service Control Manager uses CreateProcessAsUser to start the service process, so you need to point the SCM to an executable binary, as opposed to a script.

If you can't use the scheduler (though I strongly encourage you to try), I suppose that you could write an executable binary that acts as a service. It would then execute PowerShell and your script on your behalf. I'm thinking something like the srvany program that used to be included with the Windows Server 2003 Resource Kit could bootstrap the service for you.

You can use the Compile Script into Service option of PowerGUI: http://documents.software.dell.com/DOC144271

I think what you are looking for is SrvAny.exe from Microsoft (I don't know that they support it any longer, but it has been around in the Windows 2000 Resource Kit for years. It will essentially turn just about any executable (.exe, .cmd, etc...) into a service. I have VBScripts running as quasi-services using Srvany.exe and it works on Windows 2003 and Windows 2008 (even 64 bit). It is a little limited in that it does not provide 100% service functionality (stopping a running script may be difficult) but if you now a bit about programming and the Windows environment you can adapt it to work pretty well (i.e. it will launch the program after server Restart/Startup as you would likely need from a service. There is some documentation with SrvAny.exe (although it can be a little obtuse and difficult to find). It is however Free and built for Windows so it should work for you. I agree for simplicity that the Scheduled Task idea is worth thinking about as it is even more simplistic that srvany.exe

http://www.firedaemon.com/

Will allows you start littery anything as a service. There are also free alternatives to this application, that does the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!