0

I am trying to execute powershell script and capture the formatted output from powershell into C# console window but always return null.

C# Code:

    public List<SplunkEvent> events { get; set; } = new List<SplunkEvent>();

    public void InvokeCrawl()
    {
        try
        {
            List<UrlTracker> urls = new List<UrlTracker>();
            urls.Add(new UrlTracker() {  AirId = "4812", SiteId = "6976843556", Url = "https://test.com/homepage", RequestorEnterpriseId = "asif.iqbal.khan" });
            RunScript("4812", "asif", "iqbal", "pinku", "", urls);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private void RunScript(string airID, string requestorEnterpriseId, string areaLeadEnterpriseId, string mDEnterpriseId, string serviceLeadEnterpriseId, List<UrlTracker> urls)
    {
        string _path = AppDomain.CurrentDomain.BaseDirectory + "Script\\Test.ps1";
        System.IO.StreamReader sr = new System.IO.StreamReader(_path);

        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();

        Pipeline pipeline = runspace.CreatePipeline();
        Command myCommand = new Command(_path);
        CommandParameter _airId = new CommandParameter("AirId", airID);
        myCommand.Parameters.Add(_airId);
        CommandParameter _url = new CommandParameter("SiteUrl", urls[0].Url);
        myCommand.Parameters.Add(_url);

        pipeline.Commands.Add(myCommand);
        //pipeline.Commands.AddScript(sr.ReadToEnd());
        pipeline.Commands.Add("Out-String");
        var results = pipeline.Invoke();
        runspace.Close();
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }

        Console.WriteLine(stringBuilder.ToString());
    }

Test.ps1 Code:

enter image description here

Output from C#: enter image description here

Executing the script directly inside windows powershell i could see the result getting printed. enter image description here

Community
  • 1
  • 1
Asif Iqbal
  • 531
  • 8
  • 28

1 Answers1

1

In your Powershell script, use Write-Output instead of Write-Host

You can also remove this line from the C# code.

pipeline.Commands.Add("Out-String");

More info on the difference between the two here: PowerShell difference between Write-Host and Write-Output?

colinD
  • 1,641
  • 1
  • 20
  • 22