[英]System.InvalidProgramException when trying to run Powershell commands in C#
I have ran a debug stepping through the program and it crashes at the following line 我在程序中运行了调试步骤,并在以下行崩溃
Runspace runspace = RunspaceFactory.CreateRunspace();
It gives the following error 它给出了以下错误
An unhandled exception of type 'System.InvalidProgramException' occurred in PrimarySMTP_Fix.exe
Additional information: Common Language Runtime detected an invalid program.
This is my first time working with Power Shell through C# and I'm having trouble getting some simple code execution. 这是我第一次通过C#与Power Shell一起工作,而我在获取一些简单的代码执行方面遇到了麻烦。 The point of the project is to automate a simple fix for a common issue with our company's exchange server. 该项目的重点是针对我们公司的交换服务器自动解决常见问题。
The complete code is below. 完整的代码如下。
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);
}
}
}
The above is just setup to test. 以上只是测试设置。 For now it's taking just the username information and running it directly as a command. 现在,它仅接受用户名信息,并直接将其作为命令运行。 If I can get that to work and output information then I can re-write it to do what I want it to do. 如果我可以使它正常工作并输出信息,则可以将其重写以执行我想要的操作。
After playing around for a while I found that I needed to reinstall the Windows Management Framework to get it to work. 玩了一段时间后,我发现我需要重新安装Windows Management Framework才能使其正常工作。 Figured that out when I put the debug build on the server and ran the test there and it worked. 当我将调试版本放到服务器上并在服务器上运行测试时,就知道了这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.