[英]Execute Powershell Script from C# with users input command line
I created a website that does remotely execute powershell to specific server. 我创建了一个网站,该网站可以对特定服务器远程执行Powershell。 I would like to know how it work to pass 2 user selected values to commandline from dropdownlist on asp.net website along with powershell script file?
我想知道如何将2个用户选择的值与powershell脚本文件一起从asp.net网站上的dropdownlist传递到命令行的工作方式? I already have working code with powershell script file but now adding 2 arguments in script file.The powershell arguments is,
我已经在Powershell脚本文件中使用了工作代码,但是现在在脚本文件中添加了2个参数。
[string]$ContainerIn=$args[0]
[int]$ips2get=$args[1]
Here a C# working codes, 这是一个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;
}
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. powershell脚本参数将获取容器和numIPs变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.