我有类来保持PowerShell会话。这样我就可以在不创建新会话的情况下访问powershell会话。以下是我的代码段
public class PowerShellSession : IHttpHandler, IRequiresSessionState
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
public PowerShell PowerShell2010()
{
if(HttpContext.Current.Session == null)
{
WSManConnectionInfoSession connExch = new WSManConnectionInfoSession();
var session = connExch.GetExchangeConnectionSession(2010);
Runspace runspace = RunspaceFactory.CreateRunspace(session);
runspace.Open();
PowerShell Shell = PowerShell.Create();
Shell.Runspace = runspace;
HttpContext.Current.Session["PowerShell2010"] = Shell;
return Shell;
}
if (HttpContext.Current.Session["PowerShell2010"] != null)
{
WSManConnectionInfoSession connExch = new WSManConnectionInfoSession();
var session = connExch.GetExchangeConnectionSession(2010);
Runspace runspace = RunspaceFactory.CreateRunspace(session);
runspace.Open();
PowerShell Shell = PowerShell.Create();
Shell.Runspace = runspace;
HttpContext.Current.Session["PowerShell2010"] = Shell;
return Shell;
}
else
{
return (PowerShell)HttpContext.Current.Session["PowerShell2010"];
}
}
}
问题是我的代码总是返回"对象引用未设置为对象的实例"当我尝试将值设置为session时。
这里是在会话上设置值的代码
HttpContext.Current.Session["PowerShell2010"] = Shell;
我做错了吗?
答案 0 :(得分:1)
我没有使用Powershell的经验。话虽如此,问题的很大一部分似乎是你的if()
陈述不正确。
首先检查if(HttpContext.Current.Session == null)
如果在当前上下文中找不到Session对象,则为TRUE。但是你继续尝试使用那个Session对象,所以难怪你得到了你得到的错误。
下一个似乎也是错误的:if (HttpContext.Current.Session["PowerShell2010"] != null)
,如果之前存储Powershell对象的尝试成功,则为TRUE。但是接着你继续创建和存储一个新的Powershell对象,它完全击败了你显然想要的缓存。您需要将此替换为== null
,假设您将首先找到一种方法来获取Session对象。
最后但并非最不重要的是,更有可能获得HTTP Session对象: