Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 捕获从.NET应用程序执行的powershell脚本的标准输出_C#_.net_Powershell - Fatal编程技术网

C# 捕获从.NET应用程序执行的powershell脚本的标准输出

C# 捕获从.NET应用程序执行的powershell脚本的标准输出,c#,.net,powershell,C#,.net,Powershell,让我们假设我有一个非常简单的powershell脚本myscript.ps1,它写入standart输出: get-location 现在我想从.net应用程序执行这个脚本。我最终得到了下一个代码: var process = new Process { StartInfo = { FileName = "powershell.exe", Arguments = "-file \"myscr

让我们假设我有一个非常简单的powershell脚本
myscript.ps1
,它写入standart输出:

get-location
现在我想从.net应用程序执行这个脚本。我最终得到了下一个代码:

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();
它也能工作,但我认为使用
System.Management.Automation
assembly:

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

但是,
Invoke
返回`PSObject'的集合,我找不到方法访问“myscript.ps1”上的stdout

,放在输出字符串的末尾

这不是输出吗?尝试打印您的PSObject
foreach(PSObject结果在shell.Invoke()中){Console.WriteLine(“{0}”,result.ToString());}
@PeterSchneider tryed,在这种情况下,它是空集合
结果中的内容。成员
?另一种方法是使用
System.Diagnostics.Process
启动外部命令并重定向输出。您可以找到一个示例…@Uriil请理解
powershell.exe
不仅输出结果,而且对其进行格式化