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

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.