Why is it not possible to invoke Powershell as a regular process in C#

Viewed 358

Wanted to know if there is a reason that Powershell needs a special library (in System.Management.Automation NS) to be invoked from C# code? I have this code:

        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;

        string trackerPath = "C:\\Users\\bernam\\Downloads\\test_scripts\\test_scripts\\Mindaugas_Scripts\\test.ps1";
        p.StartInfo.FileName = "Powershell.exe";
        p.StartInfo.Arguments = " -file " + trackerPath;

        Console.WriteLine(p.StartInfo.FileName + p.StartInfo.Arguments);

        p.Start();

        string output = p.StandardOutput.ReadToEnd();

And it does not seem to be working - output is not returned back. However all these scenarios work fine (produce desired output):

  • p.StartInfo.FileName = "Powershell.exe"; p.StartInfo.Arguments = "get-service"; - works fine.
  • Invoking the PS script from the command line works fine as well (invocation from CMD):

    >Powershell.exe -file "C:\Users\<shortened>\test.ps1"
    1
    2
    

The powershell code inside the script:

1..10 | % { Write-Host $_  ; sleep -m 500}

I know that there is a recommendation to use PowerShell class in System.Management.Automation namespace. What is interesting to me - is why? And is it possible to use PS without that Class? Maybe my code is simply wrong?

2 Answers
Related