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