首页 > > > C#使用powershell的问题
最近在做一个使用powershell向SCVMM服务器发送创建虚拟机之类指令的,当出现一条指令执行失败后以后再也无法发送类似的指令。那条指令失败后Runspace关闭后,下次发送指令也还会检测Runspace的状态,如果关闭会重新打开。但SCVMM作业记录都没显示有收到这条指令。
public class PSHelper
{
public PowerShell ps = PowerShell.Create();
public PSCommand psc = new PSCommand();
public PSObject pss;
public Runspace runspace ;//RunspaceFactory.CreateRunspace();
public static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public PSHelper()
{
runspace = RunspaceFactory.CreateRunspace();
OpenRunspace();
}
public void OpenRunspace()
{
if (runspace.RunspaceStateInfo.State.ToString().Equals("Closed"))
{
runspace = RunspaceFactory.CreateRunspace();
}
if (runspace.RunspaceStateInfo.State.ToString().Equals("BeforeOpen"))
{
runspace.Open();
}
}
public void Close()
{
runspace.Close();
// ps.Dispose();//add by xiongww
if (runspace.RunspaceStateInfo.State.ToString().Equals("Opened"))
{
runspace.Close();
}
}
public PSCredential GetPSCredential(string computername, string username, string password)
{
SecureString str = new SecureString();
foreach (char ch in password)
{
str.AppendChar(ch);
}
return new PSCredential(username, str);
}
public void InitPSSession(string computername, string username, string password)
{
SecureString str = new SecureString();
foreach (char ch in password)
{
str.AppendChar(ch);
}
PSCredential credential = new PSCredential(username, str);
Hashtable htParameters = new Hashtable();
htParameters.Add("computername", computername);
htParameters.Add("credential", credential);
Collection<PSObject> collection = this.RunPowerShellLocal("new-pssession", htParameters);
this.pss = collection[0];
}
public Collection<PSObject> RunPowerShellRemote(string script)
{
Collection<PSObject> collection;
(!runspace.RunspaceStateInfo.State.ToString().Equals("Closed"))
//{
this.psc.Clear();
ScriptBlock block = ScriptBlock.Create(script);
this.psc.AddCommand("invoke-command");
this.psc.AddParameter("scriptBlock", block);
this.psc.AddParameter("session", this.pss);
OpenRunspace();
this.ps.Commands = this.psc;
this.ps.Runspace = runspace;
collection = this.ps.Invoke();
return collection;
}
}
}上面是执行powershell的核心代码,失败以后再发送指令过去“collection”接受到的值都为空
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2349/viewspace-3147385/ ,如需转载,请注明出处,否则将追究法律责任。