有时,无论您是否登录到计算机,您都需要一个应用程序或脚本来继续运行。也许它是一个PowerShell 脚本来监视端口(PowerShell script to monitor ports)或在您的家庭网络上托管一个页面的 Web 服务器(web server hosting a page on your home network)。
关键是,如果您希望进程、脚本或程序在计算机开启时运行,您需要创建一个Windows 服务(Windows Service)。
创建 Windows 服务需要什么?(What Do I Need to Create a Windows Service?)
要在Windows 10(Windows 10)中创建Windows服务,有几个先决条件:
- 计算机上的管理员(Administrator)访问权限
- 作为服务运行的东西(PowerShell脚本(PowerShell Script)、程序等)
- 已安装非吸吮服务管理器(Service Manager)( NSSM )
什么是非吸吮服务经理?(What Is the Non-Sucking Service Manager?)
是的,你不能不解释就放弃这样的名字。当然这个名字是不幸的,但它是准确的。Non-Sucking Service Manager ( NSSM ) 可以说是创建高度可靠和可配置的Windows服务的最简单方法。(Windows)此外,它是免费的开源软件(Open Source Software)(OSS)。
NSSM 可以通过Windows 命令提示符(Windows Command Prompt)或图形用户界面 ( GUI ) 使用。这意味着任何人都可以使用它。NSSM 可用于任何版本的Windows,包括Windows 2000。有32 位和 64 位(32-bit and 64-bit)版本。如果您使用的是 64 位计算机,请先尝试该版本。如果它不起作用,请回退到 32 位版本。
您可以从网站下载 NSSM(download NSSM from the website),从 Git 克隆 NSSM(clone NSSM from Git),或使用 Chocolatey 安装 NSSM(install NSSM with Chocolatey)。Chocolatey 是 Windows 的包管理器(Chocolatey is a package manager for Windows)。安装(Installation)方法将根据您采用的路线而有所不同。请(Please)查阅NSSM的说明。对于我们的示例,我们从NSSM网站下载并将其安装在C:\WINDOWS\system32中。
使用 NSSM 创建 Windows 服务(Create a Windows Service With NSSM)
对于此示例,我们将使用PowerShell 脚本(PowerShell script)创建一个服务来记录CPU 平均负载百分比(CPU average load percentage)。
- 将此脚本作为log-CPULoadPercentage.ps1复制并保存到其他人不太可能访问的位置。尝试创建目录C:/Scripts 并将其存储在那里。此外,在Scripts(Scripts)中创建一个名为Logs的文件夹。请注意,脚本的路径是C:/Scripts/log-CPULoadPercentage.ps1。稍后您将需要它。
注意(Note):下面所有跟 # 符号的行都是注释,不会影响脚本。
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
- 这可以在Windows 命令提示符(Windows Command Prompt)或PowerShell 中完成。(PowerShell. )以管理员身份打开它(Open it as Administrator)。
- 输入命令nssm install logCPUAvg并运行它。NSSM 服务安装程序(NSSM service installer)窗口将打开。
- 单击(Click)Path:字段旁边的省略号按钮,导航到通常位于C:\Windows\System32\powershell.exe。选择 powershell.exe。路径:(Path:)和启动目录:(Startup directory:)字段将自动填充。
- 在Arguments:(Arguments:)字段中输入以下内容: -ExecutionPolicy Bypass -NoProfile -File “C:\PathToScript\get-Script.ps1”,其中最后一部分是PowerShell脚本的路径和脚本名称。
- 选择详细信息(Details)选项卡。在“显示名称:(Display name: ) ”字段中输入您希望服务在Windows 服务(Services)管理器中显示的内容。然后,在描述:(Description:)字段中输入它的作用。启动类型:(Startup type: )可设置为Automatic、Automatic (Delayed Start)、Manual或Disabled。对于这个练习,自动(Automatic)是好的。
- 选择登录(Log on )选项卡。选择此帐户(This account):单选按钮并输入服务将运行的帐户和密码。您需要选择一个运行该服务的帐户。理想情况下,您将创建一个专门用于运行此服务的Windows帐户。此帐户的权限应仅限于服务需要执行的操作。您可以选择本地系统帐户(Local System account),但出于安全原因不建议这样做。
还有其他几个选项卡可用于自定义服务。对于本练习,这些选项卡中的默认值就足够了。选择安装服务(Install service )按钮。
- 安装服务后,您会看到Service “logCPUAvg” installed successfully! 窗户。选择确定(OK)将其关闭。至此安装结束。
- 打开Windows 服务管理器(Windows Services Manager )并确保该服务在那里。
- 运行(Run)服务以确保它能够运行。
- 要验证此服务是否正在运行,请使用文件资源管理器(File Explorer )导航到应该保存日志的位置以查看它是否存在。
nssm-check-log.png
使用 NSSM 删除 Windows 服务(Removing a Windows Service With NSSM)
也许您不再需要监控您的 CPU(monitor your CPU)负载,因此您想摆脱该服务。幸运的是,NSSM让这一切变得简单。
- 在Windows 服务管理器(Windows Services Manager)中,停止服务。为此,请选择Log CPU Average Load服务,然后选择工具栏中的方形停止按钮或左侧的停止服务链接。(Stop the service)
- 以管理员身份打开Windows 命令提示符(Windows Command Prompt )或PowerShell 。
- 输入命令nssm remove logCPUAvg并执行命令。
- NSSM会要求您确认。选择是(Yes)。
- 删除服务后,您会看到Service “logCPUAvg” removed successfully! 确认。选择确定(OK),您就完成了。
就这样。检查服务管理器以确保服务不再存在是个好主意。如果您仍然看到该服务,则可能需要刷新屏幕,它应该会消失。
服务是运行应用程序或脚本的好方法,这些应用程序或脚本需要一直运行,如果失败则重新启动,或者需要与当前用户不同的权限。如果您不需要您的应用程序或脚本来执行所有这些操作,请考虑改用计划任务(using a Scheduled Task)。
How To Create a Windows Service
Sometimes you need an app or ѕcript to keep running whether you’re logged іntо your computer or not. Maybe it’s a PowerShell script to monitor ports or a web server hosting a page on your home network.
The point is that if you want a process, script, or program to run as long as the computer is on, you’ll need to create a Windows Service.
What Do I Need to Create a Windows Service?
To create a Windows service in Windows 10, there are a few prerequisites:
- Administrator access on the computer
- Something to run as a service (PowerShell Script, program, etc.)
- Non-Sucking Service Manager (NSSM) installed
What Is the Non-Sucking Service Manager?
Yes, you can’t drop a name like that without explaining it. Sure the name is unfortunate, yet it is accurate. The Non-Sucking Service Manager (NSSM) is arguably the easiest way to create a Windows service that is both highly reliable and configurable. Plus, it’s free and Open Source Software (OSS).
NSSM can be used through the Windows Command Prompt, or a graphical user interface (GUI). This means anyone can use it. NSSM can be used on any version of Windows going back to, and including, Windows 2000. There are 32-bit and 64-bit versions. If you’re using a 64-bit computer, try that version first. If it doesn’t work, fall back to the 32-bit version.
You can download NSSM from the website, clone NSSM from Git, or install NSSM with Chocolatey. Chocolatey is a package manager for Windows. Installation methods will vary depending on which route you take. Please consult NSSM’s instructions. For our example, we’re downloading from the NSSM website and installing it in C:\WINDOWS\system32.
Create a Windows Service With NSSM
For this example, we’ll create a service out of a PowerShell script to log CPU average load percentage.
- Copy and save this script as log-CPULoadPercentage.ps1 to a place that’s not likely to be accessed by anyone else. Try creating the directory C:/Scripts and storing it there. Also, create a folder in Scripts called Logs. Note that the path to the script is C:/Scripts/log-CPULoadPercentage.ps1. You’ll need that later.
Note: All lines below followed by the # symbol are comments and won’t affect the script.
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
- This can be done in either the Windows Command Prompt or PowerShell. Open it as Administrator.
- Enter the command nssm install logCPUAvg and run it. The NSSM service installer window will open.
- Click on the ellipses button next to the Path: field, navigate to the powershell.exe that’s normally located at C:\Windows\System32\. Select powershell.exe. The Path: and Startup directory: fields will be automatically populated.
- Enter the following in the Arguments: field: -ExecutionPolicy Bypass -NoProfile -File “C:\PathToScript\get-Script.ps1”, where the last part is the path to your PowerShell script and the script name.
- Select the Details tab. Enter what you’d like the service to show up as in the Windows Services manager into the Display name: field. Then, enter what it does in the Description: field. The Startup type: can be set as Automatic, Automatic (Delayed Start), Manual, or Disabled. For this exercise, Automatic is good.
- Select the Log on tab. Select This account: radio button and enter the account and password that the service will run as. You’ll need to choose an account under which the service will run. Ideally, you’ll have a Windows account created just for running this service. This account’s permissions should be limited to only what the service needs to do. You can choose the Local System account, but it’s not recommended for security reasons.
There are several other tabs that can be used to customize the service. For this exercise, the default values in those tabs are sufficient. Select the Install service button.
- When the service is installed, you’ll see the Service “logCPUAvg” installed successfully! window. Select OK to close it. That concludes the installation.
- Open the Windows Services Manager and ensure the service is there.
- Run the service to ensure it will run.
- To verify that this service is running, use File Explorer to navigate to where the log is supposed to be saved to see if it exists.
nssm-check-log.png
Removing a Windows Service With NSSM
Maybe you don’t need to monitor your CPU load anymore, so you’d like to get rid of the service. Fortunately, NSSM makes that easy.
- In the Windows Services Manager, stop the service. Do this by selecting the Log CPU Average Load service then either selecting the square stop button in the toolbar or the Stop the service link on the left side.
- Open either the Windows Command Prompt or PowerShell as Administrator.
- Enter the command nssm remove logCPUAvg and execute the command.
- NSSM will ask you to confirm. Select Yes.
- When the service is removed, you’ll see the Service “logCPUAvg” removed successfully! Confirmation. Select OK and you’re done.
That’s all. It’s a good idea to check the services manager to ensure the service is no longer there. If you still see the service, you may need to refresh the screen and it should be gone.
Services are a great way to run apps or scripts that need to run all the time, restart themselves if they fail, or need privileges different from the current user. If you don’t need your app or script to do all of those things, consider using a Scheduled Task instead.