I want to restart a windows service based on an SQL query (MS SQL Server). Details of the use case are at the bottom. Can someone please suggest a CMD/Powershell query for that? I will run that query on a scheduler.
.
.
Use Case: The service "BcMsg" has to run 24x7 and perform some required tasks. When it throws an error, the service is running but is not doing its job. We need to restart it in that case. To check if it has run into an error, we can check its execution log in an SQL database.
Here is an explainer of the desired solution:
IF EXISTS(
SELECT 1
FROM [BcTable].[dbo].[LOG]
WHERE [EntryDate] >= DATEADD(MINUTE,-5,GETDATE()) AND [EntryMsg] LIKE '%Error%'
)
THEN
RESTART BcMsg.exe
ELSE
KEEP CHILLING
You can do this in Powershell quite neatly with the Invoke-SqlCmd
command:
if ( ( Invoke-Sqlcmd -HostName YourServer -Database YourDB -Query "SELECT 1 FROM [BcTable].[dbo].[LOG] WHERE [EntryDate] >= DATEADD(MINUTE,-5,GETDATE()) AND [EntryMsg] LIKE '%Error%'").Length -gt 0)
{
Restart-Service -Name YourServiceName
}