locked
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);
                Console.Read();
    }
    private static string RunScript(string scriptText)
            {
                // create Powershell runspace
    
                Runspace runspace = RunspaceFactory.CreateRunspace();
                // open it
                runspace.Open();
                
                // create a pipeline and feed it the script text
    
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");
                pipeline.Commands.AddScript(scriptText);
                
                // 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.
    
                pipeline.Commands.Add("Out-String");
    
                // execute the script
    
                Collection <PSObject> results = pipeline.Invoke();
                pipeline.Streams.ClearStreams();
                // close the runspace
    
                runspace.Close();
    
                // convert the script result into a single string
    
                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }
    
                return stringBuilder.ToString();
            }
    

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

    Wednesday, December 20, 2017 3:29 AM