我是在 C# 环境中使用 powershell 的新手。我已经创建了一个多行文本框来输入 powershell 脚本来执行它,它运行良好。现在我想摆脱在文本框中输入并选择 3 个变量(Container 和 NumIP)而不是传递给 powerscript 脚本文件然后执行它。如何获取这些文件并将这些变量传递给 C# 中的 powershell 脚本文件?还是我必须在 C# 中创建一个脚本字符串?
这是一个工作的 powershell 脚本文件,因为它的代码很长,我将在我想要将这 2 个变量传递给这 2 个参数的地方放置 1 行代码。
[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;