HOWTO · PowerShell

如何在 PowerShell 中创建和运行服务

本教程将讨论如何在 PowerShell 中创建和运行服务。

本页内容

服务是系统自动生成的用于执行特定任务的后台程序。但通过使用 PowerShell,我们可以手动创建服务。

在本文中,我们将看到如何使用 PowerShell 手动创建服务。同时,我们通过使用示例和解释来简化主题。

使用 PowerShell 创建并运行服务

在下面的示例中,我们将创建一个名为 TestService 的简单服务。下面是我们示例的代码。

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
}

上述 PowerShell 脚本每一行的目的作为注释。执行上述示例代码后,您将获得如下输出。

使用下面的命令执行程序。

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

测试服务

要检查服务是否包含,转到您系统的服务并按名称查找该服务。