有时候,无论您是否登录计算机,都需要一个应用程序或脚本来保持运行。可能是PowerShell脚本以监视端口 或在您的家庭网络上托管页面的Web服务器 。
关键是,如果您希望只要打开计算机就可以运行进程,脚本或程序,则需要创建Windows服务 。

创建Windows服务需要什么?
要在Windows 10中创建Windows服务,需要满足一些先决条件:
什么是非吸吮服务管理器?
是的,您不能在不解释的情况下删除这样的名称。当然这个名字很不幸,但还是准确的。可以说,非吸吮服务管理器(NSSM)是创建高度可靠且可配置的Windows服务的最简单方法。另外,它是免费的,而且是开源软件 (OSS)。

NSSM可以通过Windows命令提示符 或图形用户界面(GUI)使用)。这意味着任何人都可以使用它。 NSSM可以用于Windows 2000及以后的任何Windows版本,包括Windows2000。有32位和64位 个版本。如果您使用的是64位计算机,请先尝试使用该版本。如果不起作用,请使用32位版本。
您可以从网站下载NSSM ,从Git克隆NSSM 或用Chocolatey安装NSSM 。 Chocolatey是Windows的软件包管理器 。安装方法会根据您选择的路线而有所不同。请查阅NSSM的说明。对于我们的示例,我们从NSSM网站下载并将其安装在C:\ WINDOWS \ system32中。
In_content_1全部:[300x250] / dfp: [640x360]->使用NSSM创建Windows服务
在此示例中,我们将使用PowerShell脚本 创建一个服务以进行记录CPU平均负载百分比 。
注意:下面的所有行后跟#符号均为注释,不会影响脚本。
CLS #Optional. I like to use this to clear the terminal when testing.#Make sure you have a folder called Logs in the same directory as this script #The log is where the records will be stored. Start-Transcript -Path "$PSScriptRoot\Logs\log-CPULoadPercentage-$(get-date -f yyyy-MM-dd).txt" -Append #While loop keeps it running until manually stopped While ($True){ #Creates a timestamp to know when the measurement was taken $timeStamp = get-date -f yyyy-MM-h:mm:ss #Gets the average load percentage at that time, then waits 5 seconds to do it again. $cpuLoadPercent = Get-CimInstance win32_processor | Measure-Object -Property LoadPercentage -Average | Select-Object Average;Start-Sleep -Seconds 5 #Isolates just the average so there isn't a weird @{Average=13} string $cpuLoadPercent = $cpuLoadPercent.Average #writes results to screen, or in this case to the log Write-Host "$timeStamp CPU Load Percentage $cpuLoadPercent" } Stop-Transcript




还有其他一些选项卡可用于自定义服务。对于此练习,这些选项卡中的默认值就足够了。选择安装服务按钮。




nssm-check-log.png
删除Windows服务使用NSSM
也许您不再需要监控您的CPU 加载,因此您希望摆脱该服务。幸运的是,NSSM使这变得容易。




仅此而已。检查服务经理以确保不再提供该服务是个好主意。如果仍然看到该服务,则可能需要刷新屏幕,并且应该消失了。
服务是一种运行需要始终运行的应用程序或脚本的好方法,如果它们失败,请自行重启,或需要不同于当前用户的特权。如果您不需要应用程序或脚本来完成所有这些操作,请考虑使用使用计划任务 。