使用用户输入命令行从C#执行Powershell脚本

时间:2013-11-18 20:43:53

标签: c# asp.net powershell

我创建了一个远程执行PowerShell到特定服务器的网站。我想知道如何将来自asp.net网站下拉列表中的2个用户选择值传递给命令行以及powershell脚本文件? 我已经有了PowerShell脚本文件的工作代码,但现在在脚本文件中添加了2个参数.poworhell参数是,

    [string]$ContainerIn=$args[0]
[int]$ips2get=$args[1]

这是一个C#工作代码,

//These 3 input varaibles will pass to powershell script to get specific results
        string env = "";
        string container = "";
        string numIPs = "";

        //assign dropdown selected value to variable to pass to script
        container = DropDownListContainer.SelectedValue;
        numIPs = DropDownListIP.SelectedValue;

        if (container == "H02" || container == "H07" || container == "H08")
        {
            env = "Prod";
        }
        else
        {
            env = "NonProd";
        }

        // Create a Powershell
        Runspace runSpace = RunspaceFactory.CreateRunspace();
        runSpace.Open();
        Pipeline pipeline = runSpace.CreatePipeline();

        Command invokeScript = new Command("Invoke-Command");


        RunspaceInvoke invoke = new RunspaceInvoke();

        //Add powershell command/script functions into scriptblock
        //Somewhere on this codes that it need to add command line to go with Get-FreeAddress.ps1 file script

        ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1}")[0].BaseObject as ScriptBlock;
        //ScriptBlock sb = invoke.Invoke("{" + PowerShellCodeBox.Text + "}")[0].BaseObject as ScriptBlock;

        invokeScript.Parameters.Add("scriptBlock", sb);
        invokeScript.Parameters.Add("computername", TextBoxServer.Text);

        pipeline.Commands.Add(invokeScript);

        Collection<PSObject> output = pipeline.Invoke();

        //splitting results in new lines
        foreach (PSObject psObject in output)
        {

            str = str + psObject + "\r\n";
            //str = psObject + "\r\n";
            //str += "\n" + psObject;
            //str = str + Environment.NewLine + psObject;

        }

        if (str == "")
        {
            str = "Error";

            ResultBox.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
        }

        //print out powershell output result
        ResultBox.Text = str;

    }

1 个答案:

答案 0 :(得分:0)

我终于完成了这项工作,

我只需要修改为

ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1 '"+container+"' "+numIPs+"}")[0].BaseObject as ScriptBlock;

powershell脚本参数将获取容器和numIPs变量。