0

I am new to using powershell in C# environment. I already created a multiline textbox to type powershell script to execute it and it worked fine. Now I want to get rid of typing in textbox and have 3 selected variables (Container, and NumIP) instead to pass to powerscript script file then execute it. How can I get these file and pass these variables to powershell script file in C#? Or do I have to create a script string in C#?

Here a working powershell script file, since it long codes, I am gonna put 1 line code where I want to pass these 2 variables to these 2 arguments.

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

Here a C# codes,

protected void ExecuteCode_Click(object sender, EventArgs e)
    {
        // Clean the Result TextBox
        ResultBox.Text = string.Empty;
        ResultBox.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

        string str = "";

        //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
        ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1}")[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;

    }

I know I would probably have to change this code, ScriptBlock sb = invoke.Invoke("{" + PowerShellCodeBox.Text + "}")[0].BaseObject as ScriptBlock;

2 Answers 2

1

One way would be to modify your scriptblock creation like so:

string sbstr = String.Format("{D:\Scripts\Get-FreeAddress.ps1 -Env:"{0}" -Container:"{1}" -NumIPs:{2} -GiveInfo:$false}", envTB.Text, contTB.Text, numipTB.Text);
ScriptBlock sb = invoke.Invoke(sbstr)[0].BaseObject as ScriptBlock;

In order to get the local script file propagated to the remote computer to run, you will need to do this instead:

Command invokeScript = new Command("Invoke-Command");
invokeScript.Parameters.Add("computername", TextBoxServer.Text);
invokeScript.Parameters.Add("filepath", "D:\Scripts\Get-FreeAddress.ps1");
invokeScript.Parameters.Add("argumentlist", new[]{envTB.Text, contTB.Text, numipTB.Text, False});
Sign up to request clarification or add additional context in comments.

10 Comments

What about the script file? Should I add something like string script = @"D:\Scripts\Get-FreeAddress.ps1"; then add invokeScript.Parameters.Add(script);?
No, you can just pass the full path to the script in the scriptblock.
like what? Pass script to Command invokeScript = new Command(script);?
Look at the updated answer. I assume although you have not stated as such, that you still want to run the script on a remote computer which is why you are using Invoke-Command. BTW is the script on the remote computer or is it only on the local computer?
Yes I want to run a script on a remote computer(website). The script is stored in local computer where all these VS files are.
|
0

I finally made this work,

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

The powershell script argument will get container and numIPs variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.