如何在c#中添加Powershell SnapIn

时间:2011-11-24 08:15:22

标签: c# powershell snap-in

我有一个Powershell脚本,它存储在名为“script”的字符串中,内容为:

get-user |  out-file C:\Users\user\Desktop\user.txt -append

我的C#代码:

RunspaceConfiguration runConfig = RunspaceConfiguration.Create();
                PSSnapInException psEx = null;
                runConfig.AddPSSnapIn("VMWare.View.Broker", out psEx);
                Runspace runspace = RunspaceFactory.CreateRunspace(runConfig);
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);
                Collection<PSObject> results = new Collection<PSObject>();
                results = pipeline.Invoke();
                runspace.Close();

如果我调试代码,我会得到以下异常:

No snap-ins have been registered for Windows Powershell Version 2

如果我手动运行脚本并添加管理单元,则可以正常运行

2 个答案:

答案 0 :(得分:5)

该错误消息还意味着您正在尝试从64位PowerShell实例加载32位snapin(反之亦然。)在您的情况下,您需要编译程序以定位正确的位数:x86。 AnyCPU默认为机器的位数,即64位。

答案 1 :(得分:1)

我有类似的问题...... 我试图从控制台应用程序执行自定义PowerShell cmdlet。我验证我的控制台设置为4.0框架,powershell是3.0。 事实证明,控制台的bild选项卡中的“首选32位”设置问题设置为true。我取消选中它,一切正常!