How to run powershell command in OnStart of ServiceBase Class in C#?

23 views Asked by At

I'm trying to create a custom windows service and want to run a powershell command on start. However, the powershell command failed to be triggered but the writing to the file works (so the code actually works but only failing at the powershell portion). I also fail to get output on my CLI even though I have specified Console.WriteLine()

Please help!!

$source = @"
using System;
using System.ServiceProcess;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace Testing
{
    public class MyService : System.ServiceProcess.ServiceBase
    {
        public MyService()
        {
            ServiceName = "Testing";
        }

        protected override void OnStart(string[] args)
        {
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "PowerShell.exe";
            p.StartInfo.Arguments = "-ExecutionPolicy Bypass -c & Get-Process"; // Works if path has spaces, but not if it contains ' quotes.
            p.Start();
            // Read the output stream first and then wait. (To avoid deadlocks says Microsoft!)
            string output = p.StandardOutput.ReadToEnd();
            // Wait for the completion of the script startup code, that launches the -Service instance
            p.WaitForExit(); 
            string filePath = @"C:\ProgramData\testing.txt";
            
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine("Hello, world!");
                writer.WriteLine("This is a test file.");
                writer.WriteLine("Writing to file using C#.");
            }
            
            Console.WriteLine("Hello, world!"); // Add code to perform actions when the service starts.
        }

        protected override void OnStop()
        {
            Console.WriteLine("Bye, world!"); // Add code to perform actions when the service stops.
        }
    }

    public static class Program
    {
        public static void Main()
        {
            System.ServiceProcess.ServiceBase.Run(new MyService());
        }
    }
}
"@
Add-Type -TypeDefinition $source -Language CSharp -outputAssembly "hello.exe" -OutputType ConsoleApplication -ReferencedAssemblies "System.ServiceProcess.dll"

I have tried other alternatives to trigger a powershell command from C# code based on this blog. Unfortunately, none of the suggestions worked.

0

There are 0 answers