Однако команду 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"
Подробнее здесь: https://stackoverflow.com/questions/782 ... class-in-c
Мобильная версия