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

标签 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);


    }
}
}

以上只是为了测试而设置的。目前它只获取用户名信息并直接作为命令运行。如果我能让它工作并输出信息,那么我可以重写它来完成我想要它做的事情。

最佳答案

玩了一段时间后,我发现我需要重新安装 Windows Management Framework 才能使其正常工作。当我将调试版本放在服务器上并在那里运行测试并且它有效时,我发现了这一点。

关于c# - 尝试在 C# 中运行 Powershell 命令时出现 System.InvalidProgramException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084610/

相关文章:

c# - 我如何在 C# 中的日期时间变量中只分配年份,比如 2011

c# - 按日期获取Exchange EWS托管API 2.0

c# - 是否有以编程方式远程创建 Exchange 邮箱的权威指南?

azure - 通过 powershell 的 Azure VM 的 Powerstate

xml - PowerShell:如何将InnerText值连接为单个字符串?

android - 我的 Android 应用程序应如何连接到 Exchange 服务器?

c# - 使用 ASIN 在亚马逊中获取商品/产品价格

C# System.Speech 未找到!

c# - 在 "supplied arguments"的 Queryable 上找不到 OrderBy。

Powershell IP 扫描器