C# - Windows Service run United1.ps1

Tomek 1 Reputation point
2022-01-16T19:42:25.767+00:00

Hi Guys
We have problem with script started in my C# Windows Service. My code is below.
Do not think what I am doing wrong :(

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.Configuration;
using System.Threading;
using System.IO;
using System.Collections.ObjectModel;


namespace WindowsService_Exchange_AutoResp
{
    [RunInstaller(true)]
    public partial class Service1 : ServiceBase
    {

        int ScheduleTime = Convert.ToInt32(ConfigurationSettings.AppSettings["ThreadTime"]);
        public Thread Worker = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                ThreadStart start = new ThreadStart(Working);
                Worker = new Thread(start);
                Worker.Start();
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void Working()
        {
            while(true)
            {
                string path = "D:\\sample.txt";
                using(StreamWriter writer = new StreamWriter(path, true))
                {
                    writer.WriteLine(String.Format("Moj ostatni serwices2 Tomek S Maraa "+DateTime.Now.ToString("dd/MM/yyyy HH:mm")+""));
                    writer.Close();
                }
                //d2 - DZIALA

                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.FileName = @"powershell.exe";
                //execute powershell script using script file
                //processInfo.Arguments = @"& {D:\Untiled1.ps1}";

                processInfo.Arguments = @"& {Get-Process | Out-File D:\wynik2.txt}";  //dziala
                //processInfo.Arguments = @"& {Start-Process powershell -argument '.\D:\Untiled.ps1 -UseCached -RunReport -Silent'}";
                //processInfo.Arguments = @"–ExecutionPolicy Bypass -File ""D:\Untiled1.ps1""";
                processInfo.RedirectStandardError = true;
                processInfo.RedirectStandardOutput = true;
                processInfo.UseShellExecute = false;
                processInfo.CreateNoWindow = true;

                //start powershell process using process start info
                Process process = new Process();
                process.StartInfo = processInfo;
                process.Start();

                Console.WriteLine("Output - {0}", process.StandardOutput.ReadToEnd());
                Console.WriteLine("Errors - {0}", process.StandardError.ReadToEnd());
                Console.Read();
                //koniec d2
                ////////start d3
                // Create the PowerShell object

                //koniec d3

                Thread.Sleep(ScheduleTime*60*1000);

            }
        }
        protected override void OnStop()
        {
            try
            {
                if ((Worker != null) & Worker.IsAlive)
                {
                    Worker.Abort();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 32,911 Reputation points
    2022-01-16T23:06:39.79+00:00

    Unfortunately, the United.ps1 powershell script is also not executed

    That's because you have line 58 commented out and you are actually running line 60.

    What is the D: drive? If you are trying to access it from a service, then it will need to be a local drive. If it's a drive mapped to your desktop session, then that won't work.

    Open a command prompt and run this:

    Powerhell.exe D:\Untiled1.ps1 
    

    Does that work?

    Why do you have the @ signs in front of your string variables? That does not appear to be needed.

    https://stackoverflow.com/questioons/429529/what-does-the-symbol-before-a-variable-name-mean-in-c

    Try this sequence.

                 processInfo.FileName = "powershell.exe";
                 processInfo.Arguments = "D:\Untiled1.ps1";
    
    0 comments No comments