Powershell script can not run when invoke in .NET process

32 Views Asked by At

I have one question about Powershell can not run through inside .NET Process.

I have the following Powershell

$livingDocPath = "C:\Users\chris\.dotnet\tools\livingdoc.exe"

$dllPath = "C:\Mylib\bin\Release\net6.0-windows\Mylib.dll"

$jsonPath = "C:\Mylib\bin\Release\net6.0-windows\TestExecution.json"

$command = "test-assembly"

$parameter = "-t"

& $livingDocPath $command $dllPath $parameter $jsonPath

BTW, livingdoc is a dotnet tool, which I confirmed is well installed in my machine.

This script can run through if I run it in the shell directly. The expected behavior is it will produce a html report.

But, when I try to execute this powershell script in a .NET process, it can not generate the expected result:

        static void Main(string[] args)
        {
            var binFolder = @"C:\Users\chris\Desktop\powershell";
            var arguments = Path.Combine(binFolder, "testLivingdoc.ps1");
            arguments = "-command " + arguments;
            Console.WriteLine($"script start with argument: {arguments}");

            var startInfo = new ProcessStartInfo
            {
                FileName = @"powershell",
                Arguments = arguments,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = false
            };

            using var p = Process.Start(startInfo);
            var stdError = p.StandardError.ReadToEnd();
            var stdOutput = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            if (!string.IsNullOrEmpty(stdError))
                Console.WriteLine($"powershell running error: {stdError}");
            if (!string.IsNullOrEmpty(stdOutput))
                Console.WriteLine($"powershell running result: {stdOutput}");
        }

You can see the testLivingdoc.ps1 is my script.

I tried a simple script which just prints the version of livingdoc tool,

$livingDocPath = "C:\Users\chris\.dotnet\tools\livingdoc.exe"
& $livingDocPath --version

Then it can run through inside the .NET process.

So what's happening here?

0

There are 0 best solutions below