Reputation: 38
After installing the service (.exe) and starting it, the powershell file in the code will be executed. There are also no error messages.
My Steps:
cd C:\Users\USER_XY\source\repos\ServiceApp\ServiceApp\bin\Debug\net6.0
.\ScriptAsService.exe install -servicename "MyService123" -displayname "My Service123" -description "This is my service123."
the start.txt and stop.txt will be generated but the powershell script will not be executed.
Here the c# code:
using Topshelf;
public class App
{
static void Main(string[] args)
{
var exitCode = HostFactory.Run(x =>
{
x.Service<ScriptAsService>(s =>
{
s.ConstructUsing(service => new ScriptAsService());
s.WhenStarted(service => service.Start());
s.WhenStopped(service => service.Stop());
});
x.RunAsLocalSystem();
});
}
}
public class ScriptAsService
{
private String _scriptfile = @"C:\Users\USER_XY\source\repos\ServiceApp\ServiceApp\bin\Debug\net6.0\myscript.ps1";
public void Start()
{
File.WriteAllText("start.txt", "service started --> start scriptfile=" + _scriptfile);
ProcessStartInfo process_start_info = new ProcessStartInfo();
process_start_info.FileName = "powershell.exe";
process_start_info.Arguments = this._scriptfile;
Process process = new Process();
process.StartInfo = process_start_info;
process.Start();
process.WaitForExit();
}
public void Stop()
{
File.WriteAllText("stop.txt", "service stopped");
}
}
And here the powershell code (myscript.ps1):
$counter = 0
while (1)
{
Add-Content info22.txt -Value "content = $counter"
$counter++
Start-Sleep -s 15
}
I except the info22.txt file. This file will be created by the powershell script.
Upvotes: 0
Views: 84