HOWTO · PowerShell

Como Criar e Executar um Serviço no PowerShell

Este tutorial discutirá como criar e executar um serviço no PowerShell.

Nesta página

Os serviços são o programa de fundo que o sistema gera automaticamente para realizar uma tarefa específica. Mas usando o PowerShell, podemos criar um serviço manualmente.

Neste artigo, veremos como podemos criar um serviço manualmente usando o PowerShell. Além disso, tornamos o tópico mais fácil usando um exemplo e explicações.

Criar e Executar Serviço Usando PowerShell

No nosso exemplo abaixo, criaremos um serviço simples chamado TestService. O código para o nosso exemplo está abaixo.

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
}

O propósito de cada linha do script PowerShell acima é deixado como comentários. Após executar o código de exemplo acima, você obterá uma saída como a abaixo.

Execute o programa usando o comando abaixo.

.\example.ps1 "YOUR_INSTANCE_ID"
Status   Name               DisplayName
------   ----               -----------
Stopped  TestService        TestService
Running  TestService        TestService

Serviço de Teste

Para verificar se o serviço está incluído, vá aos serviços do seu sistema e encontre o serviço pelo nome.