Come creare e eseguire un servizio in PowerShell

I servizi sono il programma di sottofondo che il sistema genera automaticamente per eseguire un compito specifico. Ma utilizzando PowerShell, possiamo creare un servizio manualmente.
In questo articolo, vedremo come possiamo creare manualmente un servizio utilizzando PowerShell. Inoltre, rendiamo l’argomento più semplice usando un esempio e spiegazioni.
Creare e Eseguire un Servizio Utilizzando PowerShell
Nel nostro esempio qui sotto, creeremo un semplice servizio chiamato TestService
. Il codice per il nostro esempio è qui sotto.
if ($args.count -eq 1) {
$Service_Name = "TestService" # Setting the service name
$Service_Root_Path = "D:\TestService\" # Setting the service root path
$Service_Path = $Service_Root_Path + "\TestService.exe" # Setting the service path
$Service_Description = "My Test Service" # Providing some description of the service
$Service_Config = $Service_Root_Path + "\appsettings.Production.json" # Service configuration
$InstanceConfig = "D:\InstanceConfig.config" # Instance configuration
(Get-Content -Path $Service_Config -Raw) -Replace "1024", $args[0] | Set-Content -Path $Service_Config
Copy-Item $InstanceConfig -Destination $Service_Root_Path
# Checking if the service already exists. If it exists, delete it.
if (Get-Service -Name $Service_Name -ErrorAction SilentlyContinue) {
Stop-Service -Name $Service_Name # Stop the service
sc.exe delete $Service_Name # Delete the service
}
New-Service -Name $Service_Name -BinaryPathName $Service_Path -Description $Service_Description
# Modify service configuration settings
[System.Environment]::SetEnvironmentVariable('ASPNETCORE_ENVIRONMENT', 'Production', [System EnvironmentVariableTarget]::Machine)
Set-Service -Name $Service_Name -StartupType Automatic
Start-Service -Name $Service_Name # Start the service
Get-Service -Name $Service_Name
}
else
{
# If the user didn't provide an InstanceId, return an error message.
$Message = "Required to specify InstanceId argument"
Write-Output $Message
}
Lo scopo di ciascuna riga del sopra menzionato script PowerShell è lasciato come commenti. Dopo aver eseguito il codice di esempio sopra, otterrete un output simile a quello qui sotto.
Esegui il programma utilizzando il comando sottostante.
.\example.ps1 "YOUR_INSTANCE_ID"
Status Name DisplayName
------ ---- -----------
Stopped TestService TestService
Running TestService TestService
Per controllare se il servizio è incluso, vai ai servizi del tuo sistema e trova il servizio per nome.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn