我想在一些网页代码中创建一个运行空间,Power shell 会话将在其中运行。我希望在用户打开页面时创建这个运行空间,并保持打开状态直到它关闭。因此,例如下面的代码是一键单击。但每次我运行 power shell 命令时,我都需要运行
"$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();
我提出的解决方案
所以我想我会尝试制作一个静态的对象,我可以调用它。我认为通过创建我第一次调用它的静态调用将运行“静态 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;
}
}