Forum Discussion
Powershell to Monitor Services
- Aug 01, 2024
#Loop through all servers and services for each server
foreach ($servername in $servernames)
foreach ($ServiceName in $ServiceNames) {
If (Get-Service -ComputerName "$servername" -Name "$ServiceName") {
$ServiceStatus = Get-Service -ComputerName "$servername" -Name "$ServiceName"
$ServiceState = $ServiceStatus.Status
ServiceCheck
}
}
}
This checks if service is there, then checks status
Adamzter81 You could use it like this: (Not tested)
#All Variables are defined below
$servernames = 'Server1', 'Server2'
$ServiceNames = 'InternalServiceName1', 'InternalServiceName1'
# All functions are defined below
Function ServiceCheck {
if
($ServiceStatus.Status -eq 'Running') { Write-Host 'Running' }
Else
{ Sendmail("Alert Triggered") }
}
Function sendMail ($message) {
"Sending Email"
#SMTP server name
$smtpServer = "smtp.office365.com"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
$emailPassword = "HiddenPassword"
$emailCredential = New-Object System.Net.NetworkCredential("email address removed for privacy reasons", $emailPassword)
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Port = 587
$smtp.EnableSSl = $true
$smtp.Credentials = $emailCredential
#Email structure
$msg.From = "email address removed for privacy reasons"
$msg.To.add("email address removed for privacy reasons")
$msg.subject = "Alert - $ServiceName on $servername is $ServiceState"
$msg.body = "$ServiceName on $servername is $ServiceState"
#Sending email
$smtp.Send($msg)
"Email Sent"
}
#Loop through all servers and services for each server
foreach ($servername in $servernames) {
foreach ($ServiceName in $ServiceNames) {
$ServiceStatus = Get-Service -ComputerName "$servername" -Name "$ServiceName"
$ServiceState = $ServiceStatus.Status
ServiceCheck
}
}
Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.
If one of the posts was helpful in other ways, please consider giving it a Like.
- Aug 01, 2024
#Loop through all servers and services for each server
foreach ($servername in $servernames)
foreach ($ServiceName in $ServiceNames) {
If (Get-Service -ComputerName "$servername" -Name "$ServiceName") {
$ServiceStatus = Get-Service -ComputerName "$servername" -Name "$ServiceName"
$ServiceState = $ServiceStatus.Status
ServiceCheck
}
}
}
This checks if service is there, then checks status- Adamzter81Aug 28, 2024Copper Contributor
This should work, I am just trying to put all the peices together and now get this working in one script
- Aug 06, 2024Any update?
- Aug 24, 2024Did that work for you?