2016-11-16 34 views
0

我想要在运行Power Shell会话的某些网页代码中创建运行空间。我希望在用户打开该页面并保持打开状态时创建此运行空间直到它关闭。因此,例如下面的代码是一个按钮点击。但每次我运行一个电源外壳命令的时间我需要运行.net(C#)中的持久运行空间

"$S = new-pssesession -configurationname micros......" 

这需要几秒钟,刚刚建立的会议,我在哪里可以创建运行空间和PowerShell对象,这样我可以从任何调用它每次我想使用它时,在代码中都不得不重新创建它。在一个控制台应用程序我会板着脸在“主”类,但它似乎网页/应用程序具有不同的结构

protected void Button1_Click(object sender, EventArgs e) 
    { 

     var runspace = RunspaceFactory.CreateRunspace(); 
     runspace.Open(); 

     var powershell = PowerShell.Create(); 
     //{ 
     powershell.Runspace = runspace; 


     powershell.AddScript("Set-ExecutionPolicy Unrestricted ; $s=new-pssession -configurationname microsoft.exchange -connectionuri http://server.com/powershell -authentication kerberos ; import-pssession $s"); 
     powershell.Invoke(); 
     powershell.AddScript("get-dynamicdistributiongroup"); 
     Collection<PSObject> resultsL = powershell.Invoke(); 


     // close the runspace 
     runspace.Close(); 

     Input.Items.Clear(); 
     foreach (var dlist in resultsL) 
     { 
      Input.Items.Add(dlist.ToString()); 
     } 

     Input.DataBind(); 

我所提出的解决方案

所以我想我会尽量让建立一个静态的对象,我可以拨打电话。我认为通过创建一个静态调用,我第一次调用它会运行“static powers()”构造,但是任何进一步的调用只会调用方法中的代码段。然而,不知道我是否完全正确。

public static class powers 
    { 

     static public Runspace runspace = RunspaceFactory.CreateRunspace(); 
     static public PowerShell powershell = PowerShell.Create(); 

     static powers() 
     { 

      runspace.Open(); 
      powershell.Runspace = runspace; 
      powershell.AddScript("Set-ExecutionPolicy Unrestricted ; $s=new-pssession -configurationname microsoft.exchange -connectionuri http://exchangeserver.com/powershell -authentication kerberos ; import-pssession $s"); 
      var resultL = powershell.Invoke(); 

     } 

     static public Collection<PSObject> glist() 
     { 


      powershell.AddScript("get-dynamicdistributiongroup"); 
      Collection<PSObject> resultL = powershell.Invoke(); 
      return resultL; 

     } 

     static public Collection<PSObject> gmembers(string listn) 
     { 

      string GetMembers = "$FTE = Get-DynamicDistributionGroup '" + listn + "'"; 
      powershell.AddScript(GetMembers); 
      powershell.Invoke(); 
      powershell.AddScript("Get-Recipient -RecipientPreviewFilter $FTE.RecipientFilter"); 
      Collection<PSObject> resultM = powershell.Invoke(); 
      return resultM; 

     } 
    } 

回答

1

我已经建立了几个其他的应用程序,我已经存储了会话中的东西并使用属性来访问它们。类似的东西可能适合你。

public static Runspace runspace 
{ 
    get 
    { 
    //if not exist, create, open and store 
    if (Session["runspace"] == null){ 
     Runspace rs = RunspaceFactory.CreateRunspace(); 
     rs.Open(); 
     Session["runspace"] = rs; 
    } 

    //return from session 
    return (Runspace)Session["runspace"]; 
    } 
} 

然后,您可以简单地将它作为事件处理程序中的静态属性进行访问。

+0

我正在尝试做类似的事情,但不确定它是否还有。干杯 – DevilWAH

+0

当我尝试这个我得到“名称会话”不存在于当前的上下文“任何指针我做错了什么? – DevilWAH

+0

排序它,只是我做一个类型大声笑所有工作很好现在谢谢你 – DevilWAH