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
サービスが含まれているかどうかを確認するには、システムのサービスに移動し、名前でサービスを見つけます。