尝试在C#中运行Powershell命令时出现System.InvalidProgramException

时间:2014-08-01 16:22:07

标签: c# powershell exchange-server

我已经通过程序运行调试,它在以下行崩溃

Runspace runspace = RunspaceFactory.CreateRunspace();

它出现以下错误

An unhandled exception of type 'System.InvalidProgramException' occurred in     PrimarySMTP_Fix.exe

Additional information: Common Language Runtime detected an invalid program.

这是我第一次通过C#使用Power Shell而且我在执行一些简单的代码时遇到了麻烦。该项目的目的是为我们公司的交换服务器的常见问题自动化一个简单的修复。

完整的代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;


namespace PrimarySMTP_Fix
{

public partial class MainWindow : Window
{
    //Variable Declarations
    string userName = "";
    string confirmUser = "";
    string primarySMTP = "";
    string confirmSMTP = "";


    public MainWindow()
    {
        InitializeComponent();
    }

    private string RunScript(string scriptText)
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();

        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(scriptText);

        pipeline.Commands.Add("Out-String");

        Collection<PSObject> results = pipeline.Invoke();

        runspace.Close();

        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }
        return stringBuilder.ToString();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        userName = adUser.Text;
        confirmUser = confirmAD.Text;
        primarySMTP = mail.Text;
        confirmSMTP = confirmMail.Text;

        outPut.Text = RunScript(userName);


    }
}
}

以上只是设置测试。现在只需要输入用户名信息并直接将其作为命令运行。如果我可以让它工作并输出信息,那么我可以重写它来做我想做的事情。

1 个答案:

答案 0 :(得分:3)

在玩了一会儿之后,我发现我需要重新安装Windows Management Framework才能让它运行起来。当我将调试版本放在服务器上并在那里运行测试并且它工作时,想出来了。