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

标签 powershell netstat

我创建了下面的脚本来检查我的应用程序的端口 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

最佳答案

我原来的回答没有考虑到你还需要实现服务控制接口(interface),powershell.exe不执行。但是,我确实研究了将 PowerShell 脚本作为服务运行的其他一些方法。

我遇到的为您执行此操作的更简单的工具之一是 nssm您可以使用 nssm (Non-Sucking Service Manager)注册一个新服务并让它运行你的 PowerShell 脚本。您需要确保您的 脚本的主逻辑在无限循环中运行 (就像大多数长时间运行的程序或服务一样),然后您可以使用 nssm注册将运行您的 PowerShell 脚本的新服务。下面是将代码放入不终止的主循环的示例:

while( $true ) {
  $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

  # Add a sleep at the end of the loop to prevent the script from eating
  # too much CPU time
  Start-Sleep -Seconds 60
}

要将您的脚本注册为 PowerShell 服务,您可以使用以下 PowerShell 代码(请注意,如果您使用 Chocolatey 安装,nssm 将已经在 PATH 上,不确定是否是手动安装时):
# 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 = C:\path\to\service\script.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

您的服务现在应该已安装并且能够像任何其他 Windows 服务一样进行控制。它的工作方式不是注册 powershell.exe直接作为服务注册nssm.exe作为服务可执行文件, 实现正确的服务控制处理程序,然后运行您为该服务配置的任何程序(在这种情况下,使用 powershell.exe 调用您的脚本)。

关于powershell - 如何将 PowerShell 脚本作为服务运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59530375/

相关文章:

powershell - 向使用 Start-Process 打开的 Powershell 发送多个参数

powershell - 如何递归获取PowerShell中自定义输出中所有文件和文件夹的大小

linux - 在 unix 服务器上运行的 netstat 命令,我应该为我的用例使用什么命令,为什么?

docker容器暴露的docker和netstat : netstat is not showing ports,

c++ - GetExtendedUdpTable 和 netstat 结果之间的区别

powershell - 如何将 Gitlab {CI_COMMIT_SHORT_SHA} 变量传递给 powershell 脚本

Powershell 在文件中 move 行

powershell - 在AD中创建用户时如何正确指定名称和属性

sockets - TCP 连接的 Recv-Q 高的原因是什么?

macos - 谁在监听 Mac OS X 上给定的 TCP 端口?