从C#中的powershell脚本中获取集合

时间:2017-08-23 13:55:43

标签: c# powershell

尝试在C#应用程序中获取一组项目作为PowerShell脚本的输出,但它不断返回一个空集合。

程序执行后

Results.Count:0

(当然,Exchange过滤列表不为空)

有人可以解释我做错了什么吗?

这是我的代码的一部分:

var rsConfig = RunspaceConfiguration.Create();
        using (var myRunSpace = RunspaceFactory.CreateRunspace(rsConfig))
        {
            var info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSSnapInException snapInException);

            myRunSpace.Open();
            using (var ps = PowerShell.Create())
            {
                //Getting existing list of blocking rules
                ps.AddScript("Get-ContentFilterPhrase | Where-Object {$_.Influence -Match 'BadWord'}| Format-Table -Property Phrase");
                var results = ps.Invoke(); //Run PS script
                //Debug!
                MessageBox.Show("Script executed!", "Script executed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                listBox1.Items.Add(results);

                Console.WriteLine("results.Count: {0}", results.Count);

                // Is there something in results?
                if (results.Any())
                {// Looking at every object in collection
                    foreach (var result in results)
                    {
                        //Debug!
                        listBox1.Items.Add("Object");
                        //Looking at every property of every object in collection
                        foreach (PSPropertyInfo propertyInfo in result.Properties)
                        {
                            //Debug!
                            listBox1.Items.Add("Property");
                            //Writing propertyes to Console
                            Console.WriteLine(string.Format("{0}: {1}", propertyInfo.Name, propertyInfo.Value));
                            continue;
                        }
                        continue;
                    }
                } else listBox1.Items.Add("Results're empty!");

0 个答案:

没有答案