如何在c#中添加Powershell SnapIn

and*_*pfr 6 c# powershell snap-in

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

get-user |  out-file C:\Users\user\Desktop\user.txt -append
Run Code Online (Sandbox Code Playgroud)

我的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();
Run Code Online (Sandbox Code Playgroud)

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

No snap-ins have been registered for Windows Powershell Version 2
Run Code Online (Sandbox Code Playgroud)

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

x0n*_*x0n 5

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