如何将 PowerShell 脚本作为服务运行? [英] How do I run a PowerShell script as a service?

查看:137
本文介绍了如何将 PowerShell 脚本作为服务运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created the script below to check my application's port 2025 and log the number of connections.

我需要此脚本作为 Windows 上名为 netstat_2025 的服务运行.有谁知道有没有这种可能?

I need this script to run as a service on Windows with the name netstat_2025. Does anyone know if there is such a possibility?

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

I do not want to use the Task Scheduler, but instead run the script as a service on Windows.

脚本 SCTT521CTO.ps1

script 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

推荐答案

我原来的回答没有考虑到您仍然需要实现服务控制接口,而 powershell.exe 没有实现.不过,我确实研究了将 PowerShell 脚本作为服务运行的其他一些方法.

My original answer failed to take into account that you still need to implement the service control interfaces, which powershell.exe does not implement. I did look into some other methods of running a PowerShell script as a service, however.

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

One of the easier tools I came across that does this for you is nssm You can use nssm (Non-Sucking Service Manager) to register a new service and have it run your PowerShell script. You'll need to make sure your script's main logic runs within an infinite loop (as most long running programs or services do), and then you can use nssm to register a new service that will run your PowerShell script. Below is an example of putting your code into a main loop that doesn't terminate:

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,不确定是不是你手动安装的时候):

To register your script as a PowerShell service, you can use the following PowerShell code (note that if you install with Chocolatey, nssm will already be on the PATH, not sure if it is when you manually install):

# 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 调用您的脚本).

Your service should now be installed and able to be controlled like any other Windows service. The way this works is instead of registering powershell.exe as a service directly, it registers nssm.exe as the service executable instead, which does implement the correct service control handlers, and then runs whatever program you configured it to for this service (in this case, calling your script with powershell.exe).

这篇关于如何将 PowerShell 脚本作为服务运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆