Calling powershell from .Net Console application RRS feed

  • Question

  • I have written a console application wherein I have called a powershell script from the console. In the powershell script I have written hello world as a return variable and it is running as expected but next time when I change the string from hello world to How are you it is not displaying the changed string. I cannot figure out myself what needs to be done to clear the pipeline or cache.
    I have used the below namespace
    using System.Management;
    using System.Management.Automation;
    using System.Collections.ObjectModel;
    using System.Management.Automation.Runspaces;

    I cleaned my project and rebuild it but still the same result is showing.
    static void Main(string[] args)
                string _str = string.Empty;
                _str= RunScript(@"C:\Powershell_Scripts\Test.ps1");
    Console.WriteLine("Input String is =" + str);
    private static string RunScript(string scriptText)
                // create Powershell runspace
                Runspace runspace = RunspaceFactory.CreateRunspace();
                // open it
                // create a pipeline and feed it the script text
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");
                // add an extra command to transform the script
                // output objects into nicely formatted strings
                // remove this line to get the actual objects
                // that the script returns. For example, the script
                // "Get-Process" returns a collection
                // of System.Diagnostics.Process instances.
                // execute the script
                Collection <PSObject> results = pipeline.Invoke();
                // close the runspace
                // convert the script result into a single string
                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                return stringBuilder.ToString();

    sleep 3
    $a = "Hello word"
    return $a

    Wednesday, December 20, 2017 3:29 AM