C# Windows Service Run script united1.ps1

C# Windows Service Run script united1.ps1
TP
  • Rejestracja:ponad 3 lata
  • Ostatnio:ponad 3 lata
  • Postów:6
0

Czesc
Chce napisać usługe Windows Service uruchamiajaca określone w kodzie skrypty .ps1 (serwis uruchamiał by skrpty na danym użytkowniku na ktorym został skonfigurowany).
Mam problem z uruchomieniem skryptu *.ps1. I szczerze powiedziawszy nie wiem co robie źle że moj *.ps1 sie nie wykonuje. Bede wdzieczny za podpowiedz.

Kopiuj
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


                Thread.Sleep(ScheduleTime*60*1000);

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

                throw;
            }
        }
    }
}

jarzi
  • Rejestracja:około 10 lat
  • Ostatnio:około 4 godziny
  • Postów:96
0

@TomiS_PL: Wydaję mi się, że Console.Read() zatrzyma przejście dalej, spróbuj usunąć. Chociaż to nie powinno mieć wpływu raczej na to, że się nie uruchomi chociaż raz. Usługa się instaluje? Czy otrzymujesz jakiś błąd? Może jeszcze warto sprawdzić co jest w .ps1 bo usługę podejrzewam, że odpalasz jako LocalSystem i nie masz informacji na jakim użytkowniku to wykonujesz


Loading...
edytowany 1x, ostatnio: jarzi
TP
  • Rejestracja:ponad 3 lata
  • Ostatnio:ponad 3 lata
  • Postów:6
0

Hej, wyprobuje po 16:00 i dam znać. Usługę instaluje na koncie XYZ majacym lokalne uprawnienia admina i na tym samym koncie usługa chodzi. Nie otrzymuje zadnego bledu. Co do *.ps1 jest prosty pobieram procesy i rzucam je do pliku thx taki plik ps1 na testy nic wiecej mi nie trzeba runt by sie zaczelo to przetwarzac.

TP
  • Rejestracja:ponad 3 lata
  • Ostatnio:ponad 3 lata
  • Postów:6
0

@jarzi: Niestety nie działa.
Poniżej kod POWERSHELL dla pliku :

Kopiuj
$WYNIK = "To dziala :D"
$WYNIK| Out-File D:\testy.txt

Kod C#

Kopiuj
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("Serwis TESTOWANIE "+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:\Untiled1.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

                Thread.Sleep(ScheduleTime*60*1000);

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

                throw;
            }
        }
    }
}

SI
  • Rejestracja:ponad 6 lat
  • Ostatnio:około godziny
  • Postów:106
0

Hej

zapisz ps1 jako exe.

a exe uruchom np tak

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "dcm2jpg.exe";

Tasmanian Devil
"Twój post prawdopodobnie zawiera niesformatowany kod - nie wklejaj bezpośrednio kodu, ale obejmuj go w odpowiednie znaczniki! (jestem botem, ten komentarz został dodany automatycznie)"
WeiXiao
  • Rejestracja:około 9 lat
  • Ostatnio:około godziny
  • Postów:5143
0
Kopiuj
process.StartInfo = new ProcessStartInfo
{
	WindowStyle = ProcessWindowStyle.Hidden,
	FileName = "powershell.exe",
	Arguments = $"-ExecutionPolicy Bypass -File \"{path}\"",
	WorkingDirectory = Path.GetDirectoryName(path)
};

a co do twojego

Kopiuj
Console.WriteLine("Output - {0}", process.StandardOutput.ReadToEnd());
Console.WriteLine("Errors - {0}", process.StandardError.ReadToEnd());

nie wiem czy to takie proste

edytowany 1x, ostatnio: WeiXiao

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.