【发布时间】:2013-12-06 13:08:38
【问题描述】:
我曾经能够调用 powershell 结果,但是当我添加第二个命令以再次调用时,它得到一个我无法再次调用的错误异常,因为它之前已经调用过 (pipeline.Invoke();)。当我需要执行第一个以获得我需要使用的结果然后再次执行它时,如何使它工作?我已经尝试过pipeline.Dispose(); 和pipeline.Commands.Clear(); 他们不起作用。
这里是 C# 代码,
protected void ButtonRequest_Click(object sender, EventArgs e)
{
HiddenName.Visible = false;
string str = "";
string ipAddress = "";
string name = "";
var tbids = (List<string>)Session["tbids"];
//create a powershell
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
RunspaceInvoke invoke = new RunspaceInvoke();
Pipeline pipeline = runSpace.CreatePipeline();
Command invokeScript = new Command("Invoke-Command");
//Add powershell script file and arguments into scriptblock
ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1 '" + DropDownListContainer.SelectedValue + "' " + DropDownListIP.SelectedValue + "}")[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();
foreach(PSObject psObject in output)
{
ipAddress = ipAddress + psObject;
foreach (var id in tbids)
{
try
{
//str += Request[id] + "\r\n";
name = Request[id];
Command invokeScript2 = new Command("Invoke-Command");
//Add powershell script file and arguments into scriptblock
ScriptBlock sb2 = invoke.Invoke(@"{D:\Scripts\Set-IPAddress.ps1 '" + ipAddress + "' " + name + "}")[0].BaseObject as ScriptBlock;
invokeScript2.Parameters.Add("scriptBlock", sb2);
invokeScript2.Parameters.Add("computername", TextBoxServer.Text);
pipeline.Commands.Add(invokeScript2);
pipeline.Invoke();
}
catch
{
}
}
}
【问题讨论】:
-
你能发布你得到的确切错误信息吗?
-
它说 InvalidPipelineStateException 被捕获,
Cannot invoke pipeline because it has been invoked earlier
标签: c# asp.net powershell