Windows services monitoring and controlling is very easy in
powershell scripting, you can easily
·
check service status
·
turn the service ON if it is not
·
Keep log of services status
To get service name open Services, Right click desired
service and select properties, and actual service name is right there as
mentioned in the figure
Here we are going to write a powershell script to check two SQL
Server services “MSSQLServer”
and “MSSQLAgent”, you can add as many services as
you want separated by comma.
We are also adding logs to an already created empty txt
file, in our case C:\services_status\Services.txt
POWERSHELL
SCRIPT
$services = 'MSSQLSERVER','MSSQLAgent' #list
of services you want to monitor
$a = get-date -DisplayHint
DateTime
$b = get-date -UFormat %Y-%m-%d
Add-Content C:\NOAA\services_status\PMB-Service.txt
"---------------------------------------------------
Dated $b
-------------------------------------------"
foreach ($service
in $services)
#loop will run times as number of services in the
list
{
$serv_status
= (Get-Service
-Name $service).Status
if($serv_status -eq
'running')
{
Add-Content
C:\services_status\Service.txt "Service $service is already running $a"
#write-host
"service $service is already running"
}
else
{
Set-Service
-Name $service
-Status Running
Start-Sleep
-Seconds 3
$serv_status1
= (Get-Service
-Name $service).Status
if($serv_status1 -ne
'running')
{
Add-Content
C:\services_status\Service.txt "Something is wrong service $service is not
started $a"
#Send-MailMessage
-from ' ' -to ' ' -Subject ' ' -Body $data -SmtpServer 'smtp.server.domain'
}
else
{
Add-Content
C:\services_status\Service.txt "Service $service is On Now $a"
#Write-Host
"Service $service is On Now"
}
}
}
Snapshot of
powershell screen is as below
OUTPUT Log
File
Output log file will look like this ……..
Other powershell related blogs
powershell excel data
No comments:
Post a Comment