windows - 如何使用 New-Service 命令将 PowerShell 脚本制作为 Windows 服务?

标签 windows powershell windows-services

所以我想使用我编写的 Powershell 脚本创建一个新的 Windows 服务,在运行时执行 powershell 脚本。这是我想要运行以提供服务的命令。

New-Service -Name "TestService" -StartupType Manual -BinaryPathName '"c:\path\to\powershell\powershell.exe -File C:\Scripts\PowerShellScript.ps1"'

当我运行此命令时,服务已成功创建,但是当我尝试此命令时:

启动服务-名称“TestService”

我收到一条错误消息,指出由于以下错误,服务无法启动:

Start-Service : Service 'TestService (TestService)' cannot be started due to the following error: Cannot start service TestService on
computer '.'.
At line:1 char:1
+ Start-Service -Name TestService
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
    + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand

有什么想法吗?

最佳答案

第一:

原因: Windows 服务 EXE 文件不是普通的 EXE 文件,它包含由 Windows 的服务控制管理器 (SCM) 调用的特定入口点。 PowerShell.exe 不包含此类条目,因此它无法按照您使用的方式工作。

第二:

存在一个名为 SRVANY 的 Microsoft 工具,或第三方的 NSSM (Non-Sucking Service Manager),允许您将代码封装为 Windows 服务。 Here是一篇解释如何将 NSSM 与 PowerShell 结合使用的文章。

将 NSSM 与 Powershell 结合使用摘要:

  • 获取 NSSM.EXE 文件(从网站、chocolatey、从 Git 源重建)
  • 使用以下代码(待测试):

$PathNSSM = (Get-Command NSSM).Source # Path to NSSM.EXE
$PathPowerShell = (Get-Command Powershell).Source # Path to PowerShell.exe
$PathScript = "C:\PowerShell_Scripts\YourScript.ps1" # Path to Your script. Be carefull it a non ending script
$ServiceName = "YourServiceName"
# Arguments for PowerShell, with your script and no personnalised profile
$ServiceArguments = '-ExecutionPolicy Bypass -NoProfile -File "{0}"' -f $PathScript 
# NSSM usage : nssm.exe install <service_name> "<path_to_exe_to_encapsulate>" "<argument1 argument2>"
& $PathNSSM install $ServiceName $PathPowerShell $ServiceArguments

我所说的无结尾脚本:

while($true) {
  #Your PS code
  Start-Sleep –Seconds 60
}

关于windows - 如何使用 New-Service 命令将 PowerShell 脚本制作为 Windows 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69368162/

相关文章:

php 在 Windows 7 上通过 nodejs 使用 lessc 编译 less 文件

windows - Metro 应用程序可以知道其他应用程序吗?

python - 在 Windows 上设置 Python 以不在 cmd 中键入 "python"

visual-studio-2008 - 如何在安装过程中注册 Windows 服务?

windows - 如何在 Windows 上查看代理设置?

windows - 使用 powershell 删除文件夹上的所有 ACL

powershell - 将 Powershell 脚本和文件包装在一起?

powershell - 如何使用Jenkins Multi-Configuration(矩阵)类型的项目?

c# - 有没有标准的方法来访问 .Net 中的 Windows 服务文件?

java - 启动 jboss windows 服务以从外部可见