如何将PowerShell脚本注册为Windows服务?以netstat_2025为例
部署端口监控服务(netstat_2025)
以下是将你的端口监控脚本注册为Windows服务的完整方案,使用NSSM工具实现(无需任务计划):
1. 端口监控脚本(SCTT521CTO.ps1)
这个脚本会记录服务器8000端口的实时连接数,生成按日期命名的日志文件,并自动清理5天前的旧日志:
$startTime = (Get-Date).ToString("dd_MM_yyyy") $LogDate = ((get-date).ToLocalTime()).ToString("yyyy-MM-ddTHH:mm:ss.fff") $hostname = hostname $portTServer = 8000 $FileTserver = netstat -ano | findstr "8000" $LogTserver = $LogDate + " - Quantidade de Conexoes na porta " + $portTServer + ": " + $FileTserver.count + " - Servidor: " + $hostname $LogTserver | Out-File -Append D:\SCTT521CTO\netstat_$startTime.log $limit = (Get-Date).AddDays(-5) $path = "D:\SCTT521CTO\*" Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
2. 服务注册脚本(service.ps1)
使用NSSM将上述监控脚本注册为名为netstat_2025的Windows服务,步骤如下:
前置准备
- 先下载NSSM工具,解压后将其所在路径添加到系统环境变量PATH中,或者在脚本中使用nssm的完整路径
- 确保运行脚本时拥有管理员权限
服务注册脚本代码
# Desired name of the service $serviceName = 'netstat_2025' # Get the full path to powershell.exe $powershellPath = ( Get-Command powershell ).Source # The path to the script you want to run as a service $serviceScriptPath = "D:\scripts\SCTT521CTO.ps1" # 注意:需填写监控脚本的实际完整路径,必须加引号 # The arguments to pass to the powershell executable each time the service starts $args = '-ExecutionPolicy Bypass -NoProfile -File "{0}"' -f $serviceScriptPath # Install the service using nssm nssm install $serviceName $powershellPath $args # See that the service is registered and check its status Get-Service $serviceName
3. 后续操作
- 运行完服务注册脚本后,可通过以下命令启动服务:
Start-Service netstat_2025 - 若需要修改服务配置(比如设置为自动启动),可以使用NSSM的编辑命令:
nssm edit netstat_2025 - 随时查看服务运行状态:
Get-Service netstat_2025
注意:监控脚本中的日志路径
D:\SCTT521CTO需要提前创建,否则脚本运行时会报错。
内容的提问来源于stack exchange,提问作者Leandro de Matos
相关产品推荐
相关产品推荐

