C#使用预先创建的对象调用Powershell [英] C# Invoke Powershell with pre-created object
本文介绍了C#使用预先创建的对象调用Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚开始使用PS,正在编写一些C#类,需要在PS中进行测试.
I've just started out with PS and are writing some C# classes which I need to test from within PS.
请注意,这些类不是CmdLets.
我想做这样的事情:
var myCustomObj = new CustomObj { Message = "Hello world" };
var ps = Powershell.Create();
ps.AddCommand("Import-Module").AddParameter("Assembly", "MyCustomAsm");
ps.AddCommand("myCustomObj.Run()").AddParameter(myCustomObj);
foreach(string str in ps.AddCommand("Out-String").Invoke<string>())
Console.WriteLine(str);
当我在传递给PS的对象上调用Run()时,结果将是打印输出"Hello world".
Where I invoke Run() on the object handed to PS, the result would be a printout "Hello world".
但是我什至不确定这是否可行(可能出于安全原因).
But i'm not even sure that this is possible (might be for security reasons).
我认为我有2个选择:
-
这都是可能的.如果是这样,请帮助我:)?
我将不得不基于现有对象生成脚本文件,并执行"AddScript(...)"以使ps执行该文件.
任何使我入门的指针都很好:).
Any pointers to get me started would be nice :).
亲切的问候.
推荐答案
我找到了解决方法:
var objs= new PSDataCollection<CustomObj> {obj};
using (var ps = PowerShell.Create())
{
ps.Runspace.SessionStateProxy.SetVariable("objList", objs);
ps.AddScript(@"$objList| ForEach { $_.Run()}");
ps.AddCommand("Out-String");
var output = ps.Invoke();
var stringBuilder = new StringBuilder();
foreach (var obj in output)
{
stringBuilder.AppendLine(obj.ToString());
}
var result = stringBuilder.ToString().Trim();
//Evaluate result.
}
这篇关于C#使用预先创建的对象调用Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文