如果我的服务正在启动或停止,我会让这段代码运行一个 powershell 脚本。
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();
}
当我从 cmd 提示符终止我的服务时它工作正常但是即使我的服务已启动并正在运行,powershell 脚本也会继续执行自身(它在计算机上附加一个文件)知道为什么吗?