编辑:我想出了如何解决我的问题的特定代码损坏部分(请参阅下面的答案),但是我仍在寻找集成Powershell和C#的资源,因此请随时发表评论或回答!
我发现a simple example使Powershell脚本可以看到您的C#对象,并且我一直在研究它。
使用以下代码:
public partial class MainWindow : Window
{
public string MyName = "Evan";
public MainWindow()
{
InitializeComponent();
MessageBox.Show(RunScript("$DemoForm | Get-Member"));
MessageBox.Show(RunScript("$DemoForm.MyName"));
MessageBox.Show(RunScript("$DemoForm.Title"));
}
private string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
runspace.SessionStateProxy.SetVariable("DemoForm", this);
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script
// output objects into nicely formatted strings
// remove this line to get the actual objects
// that the script returns. For example, the script
// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
}
我从这两行中得到了预期的结果:
MessageBox.Show(RunScript("$DemoForm | Get-Member"));
MessageBox.Show(RunScript("$DemoForm.Evan"));
但是此行不起作用(没有错误,它只返回一个空字符串):
MessageBox.Show(RunScript("$DemoForm.Title"));
知道为什么前两个有效但第三个无效吗?它是否与线程有关(必须从sta线程访问某些gui东西?)?似乎类似的功能正在与WindowsForms一起使用,作为示例代码的发布者。
另外,除了该示异常(exception),我还链接到and this one here,但我还没有在线找到许多有关链接C#和powershell的资源。最终,我试图创建一个可通过Powershell编写脚本的应用程序-是否有人知道其他优秀的在线资源或涵盖此方面的好书?
谢谢!!!!
最佳答案
我知道了! (在this video的帮助下)。上面的代码需要这一行才能工作
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread
这对我来说很有意义,我一直在STA线程和所有jaz :)上遇到麻烦。
关于c# - 无法整合Powershell和C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3482348/