3
我能夠一次調用powershell結果,但是當我添加第二個命令來再次調用時,它會得到一個錯誤異常,我不能再次調用它,因爲它已經在早期調用過(pipeline.Invoke();
)。當我需要執行第一個以獲得我需要使用的結果然後再次執行它時,如何使它工作?我已經試過pipeline.Dispose();
和pipeline.Commands.Clear();
他們不工作。如何執行兩次powershell調用?
這裏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
{
}
}
}
您可以發佈確切的錯誤信息,你得到什麼? – JaredPar
它說InvalidPipelineStateException被捕獲,'不能調用管道,因爲它已經被調用過' – StudentIT