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.
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;
}
}
}
}