PowerShell

[PowerShell] port 번호로 서비스 헬스 체크 & 미기동시 서비스 시작

띠옹떼옹 2024. 2. 19. 15:55

담당하는 장비의 nodeJS서비스가 간헐적으로 떨어지는 이슈가 발생하여 

자동으로 서비스 시작 시키기 위해 아래 poweshell 스크립트 작성 후 작업 스케줄러에 등록하여 사용하고 있음


# 로깅 용 함수 선언
# https://www.sharepointdiary.com/2019/06/create-log-file-in-powershell-script.html
Function Log-Message()
{
param
(
[Parameter(Mandatory=$true)] [string] $Message
)
 
Try {
#Get the current date
$LogDate = (Get-Date).tostring("yyyyMMdd")
 
#Get the Location of the script
If ($psise) {
$CurrentDir = Split-Path $psise.CurrentFile.FullPath
}
Else {
$CurrentDir = $Global:PSScriptRoot
}
 
#Frame Log File with Current Directory and date
$LogFile = $CurrentDir+ "\node_healthCheck_" + $LogDate + ".txt"
 
#Add Content to the Log File
$TimeStamp = (Get-Date).toString("yyyy-MM-dd HH:mm:ss:fff ")
$Line = "$TimeStamp - $Message"
Add-content -Path $Logfile -Value $Line
 
#Write-host "Message: '$Message' Has been Logged to File: $LogFile"
}
Catch {
Write-host -f Red "Error:" $_.Exception.Message
}
}
 
# 프로세스 명 체크용 변수 선언
$check_ProcessName = "node"
$temp1_ProcessName = ""
$temp2_ProcessName = ""
 
# 3200, 80 포트의 PID를 담을 변수를 선언하면서 PID를 할당한다.
$pid3200 = Get-NetTCPConnection | Where-Object {$_.LocalPort -eq 3200 -and $_.State -eq 'Listen'} | Select-Object -ExpandProperty owningprocess
$pid80 = Get-NetTCPConnection | Where-Object {$_.LocalPort -eq 80 -and $_.State -eq 'Listen'} | Select-Object -ExpandProperty owningprocess
 
# 해당 포트로 실행되고 있는 프로세스명을 할당한다.
$temp1_ProcessName = Get-Process | Where-Object {$_.Id -eq $pid3200} | Select-Object -ExpandProperty ProcessName
$temp2_ProcessName = Get-Process | Where-Object {$_.Id -eq $pid80} | Select-Object -ExpandProperty ProcessName
 
# 해당 프로세스가 실행중이 아니라면 명령어를 입력하여 실행시킨다.
if ($check_ProcessName -eq $temp1_ProcessName) {
#echo 'true'
Log-Message "XXX Service Already Start..."
}
else {
#echo 'false'
pm2 start C:\경로
#Get-Date -Format "yyyy-MM-dd HH:mm:ss" + ": Service Start"
Log-Message "XXX Service Start..."
}
 
if ($check_ProcessName -eq $temp2_ProcessName) {
#echo 'true2'
#Log-Message "YYY Service Already Start..."
}
else {
#echo 'false2'
cd C:\경로
npm run start 
#Get-Date -Format "yyyy-MM-dd HH:mm:ss" + ": Service Start"
Log-Message "YYY Service Start..."
}