title: How do I run a PowerShell script as a service?
body: <p>I created the script below to check my application's port 2025 and log the number of connections.</p>
  
  <p>I need this script to run as a service on Windows with the name <code>netstat_2025</code>. Does anyone know if there is such a possibility?</p>
  
  <p>I do not want to use the Task Scheduler, but instead run the script as a service on Windows.</p>
  
  <p>script SCTT521CTO.ps1</p>
  
  <pre><code>$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
  </code></pre>
  
  <p>script service.ps1</p>
  
  <pre><code># 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
  </code></pre>