C# 集成powershell和c时遇到问题#

C# 集成powershell和c时遇到问题#,c#,powershell,C#,Powershell,编辑:我知道了如何解决问题中特定的代码中断部分(请参见下面的回答),但我仍在寻找有关集成powershell和C#的资源,因此请随时发表评论或回答 我发现了让你的C#对象对powershell脚本可见的方法,我一直在使用它 使用以下代码: public partial class MainWindow : Window { public string MyName = "Evan"; public MainWindow()

编辑:我知道了如何解决问题中特定的代码中断部分(请参见下面的回答),但我仍在寻找有关集成powershell和C#的资源,因此请随时发表评论或回答

我发现了让你的C#对象对powershell脚本可见的方法,我一直在使用它

使用以下代码:

  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();
            }


}
但此行不起作用(没有错误,它只返回一个空字符串):

知道为什么前两个有效,但第三个无效吗?它是否与线程有关(必须从sta线程访问某些gui内容?)?对于示例代码的海报,WindowsForms似乎也使用了类似的功能

此外,除了我链接到的那个例子之外,我还无法在网上找到很多关于链接c#和powershell的资源。最终,我将尝试创建一个可通过powershell编写脚本的应用程序-有人知道其他优秀的在线资源或一本涵盖此内容的好书吗


谢谢

不应该是.Text而不是.Title

MessageBox.Show(RunScript("$DemoForm.Text"));
我明白了!(在他的帮助下)。上面的代码需要这行代码才能工作

runspace.ThreadOptions = PSThreadOptions.UseCurrentThread

这对我来说是有道理的,我一直在使用STA线程和所有那些jaz:)时遇到问题。

$DemoForm.Evan是如何工作的?该字段名为MyName?这是一个拼写错误的帖子,应该修复!你是对的,它不是:)我在代码中将它从文本改为标题,因为我使用的是wpf而不是windforms,但是$DemoForm.Text和$DemoFrom.Title都返回空字符串。谢谢你的回答!
MessageBox.Show(RunScript("$DemoForm.Text"));
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread