majan
majan

Reputation: 139

Powershell script improvement to get info about process status

I use simple script as below, in order to collect information about 3 processes which are running on my server. Whne process is not running then output from script is 0, when running is 1. I would like to improve my script and and reduce number of lines, because for each process I use separate same code, and I know that it is possible to do in one loop, but I don’t know how to improve.

$file = "D:\GrafanaScripts\results.txt"

$ServiceName1 = "ETOS1"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
$ServiceStatus = (Get-Service -Name $ServiceName1).status
if($ServiceStatus -eq "Running")
{
   # Write-Host "Running"
   echo "$time;$server;$ServiceName1;;;1"  >> $file
   }
else {
   #Write-Host "Stopped"
   echo "$time;$server;$ServiceName1;;;0"  >> $file
} 

$ServiceName2 = "ETOS1 Database"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
$ServiceStatus = (Get-Service -Name $ServiceName2).status
if($ServiceStatus -eq "Running")
{
   # Write-Host "Running"
   echo "$time;$server;;$ServiceName2;;1"  >> $file
   }
else {
   #Write-Host "Stopped"
   echo "$time;$server;;$ServiceName2;;0"  >> $file
} 

$ServiceName3 = "ETOS1 Webserver"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
$ServiceStatus = (Get-Service -Name $ServiceName3).status
if($ServiceStatus -eq "Running")
{
   #Write-Host "Running"
   echo "$time;$server;;;$ServiceName3;1"  >> $file
   }
else {
   #Write-Host "Stopped"
   echo "$time;$server;;;$ServiceName3;0"  >> $file
} 


Out-File "D:\GrafanaScripts\results.csv" -encoding utf8 
Add-Content "D:\GrafanaScripts\results.csv"  "Time;Hostname;ServiceName1;ServiceName2;ServiceName3;Status"
Add-Content "D:\GrafanaScripts\results.csv" -Value (Get-Content $file)

Results should be exported into csv file and looks like below:

Time;Hostname;ServiceName1;ServiceName2;ServiceName3;Status
2022-12-09 09:20:43;sneoshh1122;ETOS1;;;1
2022-12-09 09:20:44;sneoshh1122;;ETOS1 Database;;1
2022-12-09 09:20:44;sneoshh1122;;;ETOS1 Webserver;1

Thank you for support

Upvotes: 0

Views: 37

Answers (1)

Dom
Dom

Reputation: 418

This should do the trick. Now you have a loop through each ServiceName in the list ServiceNames.

$file = "D:\GrafanaScripts\results.txt"
$ServiceNames = "ETOS1",”ETOS1 Database“,"ETOS1 Webserver"
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"  
$server= Hostname
Foreach($ServiceName in $ServiceNames){
   $ServiceStatus = (Get-Service -Name $ServiceName).status
   if($ServiceStatus -eq "Running")
{
   # Write-Host "Running"
  echo"$time;$server;$ServiceName1;;;1"  >> $file
   }
   else {
   #Write-Host "Stopped"
   echo "$time;$server;$ServiceName1;;;0"  >> $file
} 
}

Are u copying the script to the server and runing it there locally? because this could also be done remotely on several servers parallel if desired.

Upvotes: 1

Related Questions