簡體   English   中英

Command.parameters.add-在.Net中運行Powershell

[英]Command.parameters.add - Running powershell in .Net

我正在嘗試找到一種在網頁中運行Powershell腳本/命令的方法。 在互聯網上進行短暫搜索后,我發現了System.management.Automation。我試圖在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());
    }
   */
}

Switch參數(如-Recurse )非常容易添加-只需指定參數名稱即可,無其他:

copyItem.Parameters.Add("Recurse");

就是這樣,僅此而已:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM