如何创建 Windows 服务来运行 powershell 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26506010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:46:46  来源:igfitidea点击:

How to create windows service to run a powershell script?

windowspowershellwindows-servicespowershell-2.0windows-server-2008-r2

提问by HamTheAstroChimp

I have infinite loop PowerShell (Testing purpose) script, which I want to run as a Service in Windows Server 2008 R2 (Standard).

我有无限循环 PowerShell(测试目的)脚本,我想在 Windows Server 2008 R2(标准)中将其作为服务运行。

I'm using the following command to create the Windows service,

我正在使用以下命令来创建 Windows 服务,

sc.exe create "My PS1Service" binPath= "powershell.exe -NoLogo -Path D:\TEST\test.ps1"

And the result is [SC] CreateService SUCCESS

结果是 [SC] CreateService SUCCESS

But when I try to run the service My PS1Service, it return the following error

但是当我尝试运行该服务时My PS1Service,它返回以下错误

Windows Could not srart the My PS1Service service on Local
Computer
Error 1053: The service did not respond to the start or control
request in a family

Any help here !!!

这里有任何帮助!!!

回答by Gostega

Due to the length of the articles I don't want to paste them in the answer.

由于文章的长度,我不想将它们粘贴到答案中。

Check out this post which is the most comprehensive source of info I've found regarding powershell services: https://msdn.microsoft.com/en-us/magazine/mt703436.aspx

查看这篇文章,这是我发现的有关 powershell 服务的最全面的信息来源:https: //msdn.microsoft.com/en-us/magazine/mt703436.aspx

which links to an example powershell service: http://jf.larvtheitroade.free.fr/progs/PSService.ps1

它链接到示例 powershell 服务:http: //jf.larvtheitroade.free.fr/progs/PSService.ps1

I didn't end up successfully modifying this as it was going to take me longer to read through it and understand it than it would to use a different method for my use case, but I'd certainly be going back to that if I needed to create a service in powershell in the future.

我最终没有成功地修改它,因为与为我的用例使用不同的方法相比,我需要更长的时间来阅读和理解它,但如果我需要,我肯定会回到那个地方将来在powershell中创建服务。

Also this: https://www.sapien.com/blog/2017/07/12/write-a-windows-service-in-powershell/

还有这个:https: //www.sapien.com/blog/2017/07/12/write-a-windows-service-in-powershell/

回答by JustAGuy

I've been looking all over the place for a decent way to make a PS1 into a service. Easiest way I found is with Winsw: https://github.com/kohsuke/winsw

我一直在四处寻找将 PS1 变成服务的体面方法。我发现的最简单的方法是使用 Winsw:https: //github.com/kohsuke/winsw

Works like a charm.

奇迹般有效。

回答by Net Dawg

I have had success with Non-sucking Service Manager (NSSM) as well. https://nssm.cc/

我在 Non-sucking Service Manager (NSSM) 上也取得了成功。 https://nssm.cc/