C#simple Powershell脚本返回错误:System.Management.Automation.Runspaces.PSSnapInException

时间:2017-02-07 15:04:23

标签: c# winforms powershell

我有一个简单的脚本,在加载Windows窗体时运行。它获取用户的登录名,这是应用程序中其他功能所必需的。除了这一部分,该应用程序工作正常。在我的开发机器上我完全没有问题,命令运行得很好。但是,当我在测试机器中运行应用程序时,它会抛出一个错误显示如下。

我不是一个PowerShell用户,并且对它的经验很少,但我不相信我甚至使用了它。有人可以帮我减轻这个错误吗?

  

**************异常文本************** System.Management.Automation.Runspaces.PSSnapInException:无法加载   Windows PowerShell管理单元Microsoft.PowerShell.Diagnostics因为   以下错误:无法加载文件或程序集   'Microsoft.PowerShell.Commands'或其依赖项之一。系统   找不到指定的文件。在   System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadMshSnapinAssembly(PSSnapInInfo   mshsnapinInfo)at   System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIn(PSSnapInInfo   mshsnapinInfo)at   System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIns(Collection`1   mshsnapinInfos,PSConsoleLoadException&警告)   System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.CreateDefaultConfiguration()   在   System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(PSHost   主持人)在HPSM_Assistant.HPSMAssistant.ADuser()中   C:\用户\用户\文件\代码\ HPSMAssistant \ HPSMAssistant \ Form1.cs中:线   592在HPSM_Assistant.HPSMAssistant.LoadTemplateEID()中   C:\用户\用户\文件\代码\ HPSMAssistant \ HPSMAssistant \ Form1.cs中:线   396 at HPSM_Assistant.HPSMAssistant.Form1_Load(Object sender,   EventArgs e)in   C:\用户\用户\文件\代码\ HPSMAssistant \ HPSMAssistant \ Form1.cs中:线   在System.Windows.Forms.Form.OnLoad(EventArgs e)处的208处   System.Windows.Forms.Form.OnCreateControl()at   System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
  在System.Windows.Forms.Control.CreateControl()at   System.Windows.Forms.Control.WmShowWindow(Message& m)at   System.Windows.Forms.Control.WndProc(Message& m)at   System.Windows.Forms.Form.WmShowWindow(Message& m)at   System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd,Int32 msg,   IntPtr wparam,IntPtr lparam)

System.Management.Automation - 程序集版本:3.0.0.0 -Win32版本:10.0.10586.0正确加载。 (它通过Nuget安装在c#app中。)

以下是我使用的代码:

  private string ADuser()// create Powershell runspace and run script to Get AD current username
    {

        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser");
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript("$env:UserName");
        pipeline.Commands.Add("Out-String");
        Collection<PSObject> results = pipeline.Invoke();
        runspace.Close();
        //Create string to output
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }
        return stringBuilder.ToString();

0 个答案:

没有答案