I have this code running a powershell script if my service is starting or stopped.
Timer timer1 = new Timer();
ServiceController sc = new ServiceController("MyService");
protected override void OnStart(string[] args)
{
timer1.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer1.Interval = 10000;
timer1.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
if ((sc.Status == ServiceControllerStatus.StartPending) || (sc.Status == ServiceControllerStatus.Stopped))
{
StartPs();
}
}
private void StartPs()
{
PSCommand cmd = new PSCommand();
cmd.AddScript(@"C:\windows\security\dard\StSvc.ps1");
PowerShell posh = PowerShell.Create();
posh.Commands = cmd;
posh.Invoke();
}
It's working fine when I kill my service from cmd prompt But even if my service is up and running, the powershell script continues to execute itself (it appends a file on the computer) Any idea why ?
The ServiceController.Status
property is not always live; it is lazily evaluated the first time it is requested, but (unless requested) only that time; subsequent queries to Status
will not normally check the actual service. To force this, add:
sc.Refresh();
before your .Status
check:
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
sc.Refresh();
if (sc.Status == ServiceControllerStatus.StartPending ||
sc.Status == ServiceControllerStatus.Stopped)
{
StartPs();
}
}
Without that sc.Refresh()
, if it was Stopped
(for example) initially, it will always say Stopped
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With