我想创建一个将执行以下操作的Windows服务
ON Custom_Service start:
ON Custom_Service停止:
P.S。我熟悉Powershell脚本语言
我知道如何编写所有脚本,但我不知道的部分是当你停止服务时如何运行命令的一部分,我不知道我是否在制作自我清晰,可能是另一种方法是在结束服务进程之前运行脚本
答案 0 :(得分:1)
好的,其中有3部分:
在代码中输入:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace RunPowerShell
{
public partial class Service1 : ServiceBase
{
// the thread that will work
Thread th;
// Varible for stop thread
bool RequestStop;
const int SecondToWait = 5;
const int miliToSec = 1000;
public Service1()
{
// Init
InitializeComponent();
// Create Thread by LINQ
th = new Thread(() => PowerShellRun());
// Init as start
RequestStop = false;
}
protected override void OnStart(string[] args)
{
// Log file that start Serivce
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\tryService\Log.txt", true))
{
file.WriteLine("Start: " + System.DateTime.Now);
}
// Thread Start
th.Start();
}
protected override void OnStop()
{
// Log file that Stop Serivce
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\tryService\Log.txt", true))
{
file.WriteLine("Stop: " + System.DateTime.Now);
}
// Stop the thread
RequestStop = true;
// Wait for the thread will be stop
Thread.Sleep(SecondToWait * miliToSec);
}
/// <summary>
/// Your Program in that Service
/// </summary>
public void PowerShellRun()
{
while (!RequestStop)
{
// Your progarm here such as run Powershell
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\tryService\Log.txt", true))
{
file.WriteLine("InProgress: " + System.DateTime.Now);
}
//Process.Start(@"powershell C:\tryService\Untitled2.ps1");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'C:\tryService\MyPSExecute.ps1'";
//startInfo.RedirectStandardOutput = true;
//startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
System.Threading.Thread.Sleep(SecondToWait * 1000);
}
}
}
}
将它投入使用后 构建它然后它会创建你的文件名称 .exe
获取此文件并输入url“C:\ tryService”
的someFolderRegister.Bat :(您可以删除此文件后执行一次)
sc.exe delete ProcessSpooler
sc.exe create ProcessSpooler binPath= "C:\tryService\RunPowerShell.exe" DisplayName= "Process Spooler" start= auto
您的项目“MyPSExecute.ps1”中调用的powershell文件
然后将所有文件放在同一个文件夹中