Command.parameters.add - 在.Net中运行powershell

时间:2016-04-20 12:21:59

标签: c# powershell

我正在尝试找到一种在网页中运行powershell脚本/命令的方法。经过短暂的互联网搜索后,我发现了System.management.Automation.I我正在尝试在C#中运行Powershell命令。我写了下面的代码,它工作正常,但我找不到如何添加copy-item命令的-recurse参数。

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

1 个答案:

答案 0 :(得分:1)

Switch参数(如-Recurse)非常容易添加 - 只需指定参数名称即可:

copyItem.Parameters.Add("Recurse");

就是这样,仅此而已: - )