Capturing stdout powershell script executed from .NET application

Let's say I have a very simple powershell script myscript.ps1

that writes to standard output:

get-location

      

Now I want to execute this application script from .net. I got the following code:

var process = new Process
        {
            StartInfo = {
                FileName = "powershell.exe",
                Arguments = "-file \"myscript.ps1\"",
                WorkingDirectory = Path.Combine(Environment.CurrentDirectory, "run"),
                UseShellExecute = false,
                RedirectStandardOutput = true
            }
        };

process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();

      

And it works, but I think there should be a more elegant way to do it using assembly System.Management.Automation

:

using (PowerShell shell = PowerShell.Create())
{
    shell.Commands.AddScript("myscript.ps1");
    var r = shell.Invoke();
    Console.WriteLine(r);
}

      

But it Invoke

returns the collection `PSObject 'and I cannot find a way to access stdout

+3


source to share


1 answer


In "myscript.ps1" put at the end of Out-String



-1


source







All Articles