把powershell 用成 c#是一种什么体验

 我来答
上海中法埃菲
2016-02-14 · TA获得超过1302个赞
知道小有建树答主
回答量:288
采纳率:0%
帮助的人:154万
展开全部
ublic 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;

}

}

————————————————

  如果能够帮助你,麻烦采纳

  你的采纳是我答题的动力

  ——谢谢你给我的支持!!!
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式