To Execute PowerShell script in c#

Here is the function , you just need to copy and paste in your application and you are done.

Function:

public static string RunScript(string scriptText)
{
// create Powershell runspace
Application.DoEvents();
Runspace runspace = RunspaceFactory.CreateRunspace();

// open it

runspace.Open();

// create a pipeline and feed it the script text

Pipeline pipeline = runspace.CreatePipeline();

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 results = pipeline.Invoke();
Application.DoEvents();

// close the runspace
runspace.Close();

return string.Empty;
}


Here i have to pass "scriptText" argument that contains powershell text that you want to execute.next one is the function which will return the text from powershell xml file.
please make sure you must set powershell xml file properties to "Embedded Resource" source. to do this folllow the step:

(1) Right click powershell.xml file in your web application.
(2) Click on Build Action to Embedded Resource.

Function:

public static string ReadTemplate(string snippet)
{
string xmlPath = "PowerShellCodeSnippets/";

xmlPath += snippet.ToString();

Assembly asm = Assembly.GetExecutingAssembly();
string[] resources = asm.GetManifestResourceNames();
//RWInstaller.PowerShellCodeSnippets.xml
XmlDocument xd = new XmlDocument();
TextReader xmlTextReader = new StreamReader(asm.GetManifestResourceStream("Pass PowerShell xml file path"));
xd.Load(xmlTextReader);

XmlNode snippetTextNode = xd.SelectSingleNode(xmlPath);

return snippetTextNode == null ? "" : snippetTextNode.InnerText.Trim();
}

Happy Coding...

No comments:

Post a Comment