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
서비스가 포함되어 있는지 확인하려면 시스템 서비스로 이동하여 이름으로 서비스를 찾으십시오.