我是C#环境中使用PowerShell的新手。我已经创建了一个多行文本框来键入powershell脚本来执行它,它工作正常。现在我想摆脱文本框中的输入并且有3个选定的变量(Container和NumIP)而不是传递给powerscript脚本文件然后执行它。如何获取这些文件并将这些变量传递给C#中的powershell脚本文件?或者我是否必须在C#中创建脚本字符串?
这是一个有效的PowerShell脚本文件,因为它有很长的代码,我要把1行代码放在我要将这2个变量传递给这2个参数的地方。
[string]$ContainerIn=$args[0]
[int]$ips2get=$args[1]
这里是C#代码,
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;
}
我知道我可能需要更改此代码ScriptBlock sb = invoke.Invoke("{" + PowerShellCodeBox.Text + "}")[0].BaseObject as ScriptBlock;
答案 0 :(得分:1)
一种方法是修改脚本块创建,如下所示:
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;
为了将本地脚本文件传播到远程计算机以运行,您需要这样做:
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});
答案 1 :(得分:0)
我终于完成了这项工作,
我只需要修改为ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1 '"+container+"' "+numIPs+"}")[0].BaseObject as ScriptBlock;
powershell脚本参数将获取容器和numIPs变量。