如何在C#对象中检索Poweshell脚本的结果?

时间:2018-11-26 09:09:28

标签: c# powershell

我想通过C#执行PowerShell脚本。我的脚本将在指定的位置创建一个.csv文件。下面的代码在指定的位置创建一个文件,但是我希望该代码返回一个对象,该对象具有文件具有的所有内容/数据。有可能吗?

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(@"C:\powershell.ps1");

    Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();

    pipeline.Commands.Add(scriptCommand);

    Collection<PSObject> psObjects;
    psObjects = pipeline.Invoke();
}

2 个答案:

答案 0 :(得分:0)

您愿意使用Powershell API吗?

例如:

PowerShell psinstance = PowerShell.Create();
psinstance.AddScript(scriptPath);
var results = psinstance.Invoke();

更多详细信息可以在这里找到: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

答案 1 :(得分:0)

您可以使用this command从powershell返回文件内容,然后将powershell输出写入PSDataCollection。

  private async Task<IEnumerable<string>> Process(string command)
    {
        var output = new List<string>();

        using (var powerShell = System.Management.Automation.PowerShell.Create())
        {
            powerShell.AddScript(command);

            var outputCollection = new PSDataCollection<PSObject>();

            await Task.Factory.FromAsync(
                powerShell.BeginInvoke<PSObject, PSObject>(null, outputCollection),
                result =>
                {
                    OnDeployEnd?.Invoke(this, EventArgs.Empty);
                    foreach (var data in outputCollection)
                    {
                        output.Add(data.ToString());
                    }
                }
            );

            if (powerShell.HadErrors)
            {
                var errorsReport = powerShell.Streams.Error.GetErrorsReport();
                throw new Exception(errorsReport);
            }
        }

        return output;
    }