简体   繁体   中英

How do I run a PowerShell script as a service?

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

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

You can just download NSSM from nssm.cc them:

  1. Run nssm in command line: nssm install YourServiceName

  2. Set the informations:

  • Path: Powershell path
  • Startup directory: Your script directory
  • Options: .\\yourscript.ps1 -arg1 value -arg2 value -arg3 value

在此处输入图片说明

That's it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM