如何将 PowerShell 脚本作为服务运行?

2024-03-22

我创建了下面的脚本来检查应用程序的端口 2025 并记录连接数。

我需要这个脚本作为 Windows 上的服务运行,其名称为netstat_2025。有谁知道是否有这种可能性?

我不想使用任务计划程序,而是将脚本作为 Windows 上的服务运行。

脚本 SCTT521CTO.ps1

$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

脚本服务.ps1

# 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

您可以从 nssm.cc 下载 NSSM:

  1. 在命令行中运行 nssm: nssm install YourServiceName

  2. 设置信息:

  • 路径:Powershell路径
  • 启动目录:您的脚本目录
  • 选项: .\yourscript.ps1 -arg1 值 -arg2 值 -arg3 值

就是这样。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 PowerShell 脚本作为服务运行? 的相关文章

随机推荐