C# 如何获取使用windows工具(EXE文件)返回的数据?

C# 如何获取使用windows工具(EXE文件)返回的数据?,c#,.net,powershell,output,console-application,C#,.net,Powershell,Output,Console Application,演示如何将脚本添加到PowerShell对象的管道中,以及如何异步运行脚本。事件用于处理脚本的输出 但是当我将脚本的内容从 powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}"); 到 或 结果总是显示空值。 如何获取运行EXE返回的数据 编辑:添加代码(Ctrl+C,Ctrl+V为硬键;)) 名称空间Microsoft.Samples.PowerShell.Runspaces { 使用制度; 使用System

演示如何将脚本添加到PowerShell对象的管道中,以及如何异步运行脚本。事件用于处理脚本的输出

但是当我将脚本的内容从

powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}");

结果总是显示空值。 如何获取运行EXE返回的数据

编辑:添加代码(Ctrl+C,Ctrl+V为硬键;))

名称空间Microsoft.Samples.PowerShell.Runspaces
{
使用制度;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用系统诊断;
使用系统、管理、自动化;
使用System.Management.Automation.Runspaces;
使用PowerShell=System.Management.Automation.PowerShell;
/// 
///此类包含此主机应用程序的主入口点。
/// 
内部类Runspace09
{
/// 
///此示例显示如何使用PowerShell对象运行
///生成从1到10的数字并带有延迟的脚本
///在每个编号之间。PowerShell对象的管道
///异步运行,事件用于处理输出。
/// 
///未使用该参数。
/// 
///此示例演示了以下内容:
///1.创建PowerShell对象。
///2.将脚本添加到PowerShell对象的管道中。
///3.使用BeginInvoke方法异步运行管道。
///4.使用PowerShell对象的事件来处理
///脚本的输出。
///5.使用PowerShell.Stop()方法中断
///管道。
/// 
私有静态void Main(字符串[]args)
{
Console.WriteLine(“打印从1到10的数字。按任意键停止处理\n”);
使用(PowerShell PowerShell=PowerShell.Create())
{
//向PowerShell对象添加脚本。该脚本将生成
//以半秒的间隔从1到10的数字。
AddScript(“$t=qwinsta;echo$t”);
//添加事件处理程序
//事件中,我们将让BeginInvoke为我们创建输出流。
PSDataCollection输出=新的PSDataCollection();
output.DataAdded+=新的事件处理程序(output\u DataAdded);
powershell.InvocationStateChanged+=新事件处理程序(powershell\u InvocationStateChanged);
//异步调用管道。
IAsyncResult asyncResult=powershell.BeginInvoke(null,输出);
//等待事情发生。如果用户在
//脚本已完成,然后调用PowerShell Stop()方法
//停止处理。
Console.ReadKey();
if(powershell.InvocationStateInfo.State!=PSInvocationState.Completed)
{
//停止对管道的调用。
Console.WriteLine(“\n停止管道!\n”);
powershell.Stop();
//等待显示Windows PowerShell状态更改消息。
系统.线程.线程.睡眠(500);
Console.WriteLine(“按一个键退出”);
Console.ReadKey();
}
}
}
/// 
///输出数据添加了事件处理程序。在
///数据被添加到输出管道中。它读取
///可用,并显示在控制台上。
/// 
///与此事件关联的输出管道。
///未使用参数。
私有静态无效输出_DataAdded(对象发送方,DataAddedEventArgs e)
{
PSDataCollection myp=(PSDataCollection)发送方;
收集结果=myp.ReadAll();
foreach(PSObject结果生成结果)
{
Console.WriteLine(result.ToString());
}
}
/// 
///管道状态更改时调用此事件处理程序。
///如果状态更改完成,处理程序将发出一条消息
///要求用户退出程序。
/// 
///不使用此参数。
///PowerShell状态信息。
私有静态void Powershell_InvocationStateChanged(对象发送方、PSInvocationStateChangedEventArgs e)
{
WriteLine(“PowerShell对象状态已更改:状态:{0}\n”,e.InvocationStateInfo.state);
if(e.InvocationStateInfo.State==PSInvocationState.Completed)
{
Console.WriteLine(“处理完成,按键退出!”);
}
}
}
}

如示例所示,使用分号分隔脚本中的命令。请注意,在以下步骤中有两个单独的过程:

powershell.AddScript("$t = qwinsta");
powershell.AddScript("echo $t");
但只要您添加一个脚本:

powershell.AddScript("$t = qwinsta; echo $t");
那你又回来做生意了


编辑:根据您的评论,您还有其他代码没有提供。在这一点出现在问题中之前,没有多少人可以确定。请发布您的代码。

返回的对象中仍然为空。对象?什么东西?您可能需要提供更多代码。请查看msdn链接。函数:Output_DataAdded,行:Console.WriteLine(result.ToString());结果为空。不清楚你在问什么。可能的副本也。链接到MSDN示例代码不足以知道您的代码在做什么。我使用的代码与链接完全相同(ofc one更改与AddScript一致)。关于代码正在做什么的描述在我问题的顶部和附加的链接中。什么是不清楚的(现在你把所有的东西都放在一个地方了。
namespace Microsoft.Samples.PowerShell.Runspaces
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    using PowerShell = System.Management.Automation.PowerShell;

    /// <summary>
    /// This class contains the Main entry point for this host application.
    /// </summary>
    internal class Runspace09
    {
        /// <summary>
        /// This sample shows how to use a PowerShell object to run a 
        /// script that generates the numbers from 1 to 10 with delays
        /// between each number. The pipeline of the PowerShell object 
        /// is run asynchronously and events are used to handle the output.
        /// </summary>
        /// <param name="args">The parameter is not used.</param>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating a PowerShell object.
        /// 2. Adding a script to the pipeline of the PowerShell object.
        /// 3. Using the BeginInvoke method to run the pipeline asynchronously.
        /// 4. Using the events of the PowerShell object to process the 
        ///    output of the script.
        /// 5. Using the PowerShell.Stop() method to interrupt the invocation of 
        ///    the pipeline.
        /// </remarks>
        private static void Main(string[] args)
        {
            Console.WriteLine("Print the numbers from 1 to 10. Hit any key to halt processing\n");

            using (PowerShell powershell = PowerShell.Create())
            {
                // Add a script to the PowerShell object. The script generates the 
                // numbers from 1 to 10 in half second intervals.
                powershell.AddScript("$t = qwinsta; echo $t");

                // Add the event handlers.  If we did not care about hooking the DataAdded
                // event, we would let BeginInvoke create the output stream for us.
                PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
                output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded);
                powershell.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(Powershell_InvocationStateChanged);

                // Invoke the pipeline asynchronously.
                IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);

                // Wait for things to happen. If the user hits a key before the
                // script has completed, then call the PowerShell Stop() method
                // to halt processing.
                Console.ReadKey();
                if (powershell.InvocationStateInfo.State != PSInvocationState.Completed)
                {
                    // Stop the invocation of the pipeline.
                    Console.WriteLine("\nStopping the pipeline!\n");
                    powershell.Stop();

                    // Wait for the Windows PowerShell state change messages to be displayed.
                    System.Threading.Thread.Sleep(500);
                    Console.WriteLine("\nPress a key to exit");
                    Console.ReadKey();
                }
            }
        }

        /// <summary>
        /// The output data added event handler. This event is called when
        /// data is added to the output pipe. It reads the data that is 
        /// available and displays it on the console.
        /// </summary>
        /// <param name="sender">The output pipe this event is associated with.</param>
        /// <param name="e">Parameter is not used.</param>
        private static void Output_DataAdded(object sender, DataAddedEventArgs e)
        {
            PSDataCollection<PSObject> myp = (PSDataCollection<PSObject>)sender;

            Collection<PSObject> results = myp.ReadAll();
            foreach (PSObject result in results)
            {
                Console.WriteLine(result.ToString());
            }
        }

        /// <summary>
        /// This event handler is called when the pipeline state is changed.
        /// If the state change is to Completed, the handler issues a message
        /// asking the user to exit the program.
        /// </summary>
        /// <param name="sender">This parameter is not used.</param>
        /// <param name="e">The PowerShell state information.</param>
        private static void Powershell_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e)
        {
            Console.WriteLine("PowerShell object state changed: state: {0}\n", e.InvocationStateInfo.State);
            if (e.InvocationStateInfo.State == PSInvocationState.Completed)
            {
                Console.WriteLine("Processing completed, press a key to exit!");
            }
        }
    }
}
powershell.AddScript("$t = qwinsta");
powershell.AddScript("echo $t");
powershell.AddScript("$t = qwinsta; echo $t");