I'm trying to find a way to run a powershell script / commands within a web page. After a short search over the internet I found System.management.Automation.I'm trying to run Powershell commands in C#. I wrote the following code and it works fine except I couldn't find how do I add the -recurse parameter of the copy-item command.
protected void ExecuteCode_Click(object sender, EventArgs e)
{
//Clean the result textbox
ResultBox.Text = string.Empty;
//Create the runspace
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
//Create the pipeline
Pipeline pipeline = runSpace.CreatePipeline();
//Create the commands
Command copyItem = new Command("copy-item");
copyItem.Parameters.Add("Path", "c:\\temp\\");
copyItem.Parameters.Add("Destination", "c:\\temp1\\");
//robocopy.Parameters.Add("Dest", "c:\\temp1");
pipeline.Commands.Add(copyItem);
//Execute the script
var results = pipeline.Invoke();
//display results, with BaseObject converted to string
if (results.Count > 0)
{
//We use a string builder on create our result text
var builder = new StringBuilder();
foreach (var psobject in results)
{
//Convert the base object to a string and append it to the string builder.
builder.Append(psobject.BaseObject.ToString() + "\r\n");
}
//Encode the string in HTML (Prevent security issue with 'dangerous' characters like <>)
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
/*
//Clean the result textbox
ResultBox.Text = string.Empty;
//Initialize Powershell Engine
var powershellConsole = PowerShell.Create();
//Add the script to the Powershell object
powershellConsole.Commands.AddScript(Input.Text);
//Execute the script
var results = powershellConsole.Invoke();
//display results, with BaseObject converted to string
if (results.Count > 0)
{
//We use a string builder ton create our result text
var builder = new StringBuilder();
foreach (var psobject in results)
{
//Convert the base object to a string and append it to the string builder.
builder.Append(psobject.BaseObject.ToString() + "\r\n");
}
//Encode the string in HTML (Prevent security issue with 'dangerous' characters like <>)
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
*/
}