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;