如何在 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

測試服務

要檢查是否包含該服務,請轉到您系統的服務並按名稱查找該服務。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: MD Aminul Islam
MD Aminul Islam avatar MD Aminul Islam avatar

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

相關文章 - PowerShell Service