How do I run a PowerShell script as a service?

ぃ、小莉子 提交于 2020-01-21 09:05:29

问题


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

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?

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

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

script service.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

回答1:


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.

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
}

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

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).



来源:https://stackoverflow.com/questions/59530375/how-do-i-run-a-powershell-script-as-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!