Как запустить команду powershell в OnStart класса ServiceBase на C#?C#

Место общения программистов C#
Ответить
Гость
 Как запустить команду powershell в OnStart класса ServiceBase на C#?

Сообщение Гость »

Я пытаюсь создать собственную службу Windows и хочу запустить команду powershell при запуске.
Однако команду powershell не удалось запустить, но запись в файл работает (поэтому код действительно работает, но происходит сбой только в части powershell).
Мне также не удается получить выходные данные в моем CLI, хотя я указал Console.WriteLine()
Пожалуйста, помогите!!

Код: Выделить всё

$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"
Я пробовал другие альтернативы для запуска команды powershell из кода C# на основе этого блога. К сожалению, ни одно из предложений не сработало.

Подробнее здесь: https://stackoverflow.com/questions/782 ... class-in-c
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»