Comment créer et exécuter un service dans PowerShell

Les services sont le programme de fond que le système génère automatiquement pour effectuer une tâche spécifique. Mais en utilisant PowerShell, nous pouvons créer un service manuellement.
Dans cet article, nous allons voir comment nous pouvons créer manuellement un service en utilisant PowerShell. De plus, nous rendons le sujet plus simple en utilisant un exemple et des explications.
Créer et exécuter un service en utilisant PowerShell
Dans notre exemple ci-dessous, nous allons créer un service simple nommé TestService
. Le code de notre exemple est ci-dessous.
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
}
Le but de chaque ligne du script PowerShell ci-dessus est laissé comme commentaire. Après avoir exécuté le code d’exemple ci-dessus, vous obtiendrez une sortie comme ci-dessous.
Exécutez le programme en utilisant la commande ci-dessous.
.\example.ps1 "YOUR_INSTANCE_ID"
Status Name DisplayName
------ ---- -----------
Stopped TestService TestService
Running TestService TestService
Pour vérifier si le service est inclus, allez dans les services de votre système et trouvez le service par son nom.
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