Run powershell script from C#

06/12/2012 12:51

how to run ps script from csharp
http://ctrlf5.net/?p=231

using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces; //you need to have this assembly installed (from SDK)  

 

//Powershel script execution
        public static string RunPsScript(string psScriptPath, string scriptParameters)
        {
            string psScript = string.Empty;
            if (File.Exists(psScriptPath))
                psScript = File.ReadAllText(psScriptPath);
            else
                MessageBox.Show("Wrong path for the script file");

            //tip for loadnig snapin
            RunspaceConfiguration config = RunspaceConfiguration.Create();
            PSSnapInException ex = null;

            //Project properties has to be set on x64 architecture
            config.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out ex);
           
            Runspace runspace = RunspaceFactory.CreateRunspace(config);

            // open it
            runspace.Open();

            try
            {
                // create a pipeline and feed it the script text
                Pipeline pipeline = runspace.CreatePipeline();

                var myCommand = new Command(psScript, true);
                //Add parameters to the script if defined
                if (!string.IsNullOrEmpty(scriptParameters))
                {
                    //myCommand.Parameters.Add(new CommandParameter("siteUrl", "https://mySiteCollection"));
                    string a = scriptParameters.Split(' ')[0];
                    string b = scriptParameters.Split(' ')[1];
                    myCommand.Parameters.Add(new CommandParameter(a, b));
                }

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

                // execute the script
                Collection<PSObject> results = pipeline.Invoke();

                // 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();
            }