Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Powershell SnapIn in c#

I have a Powershell Script which is stored in a string called "script" with the content:

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

My C# Code:

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();

If I debug the code I get the following exception:

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

If I run the script manually and add the snap-in it works fine

like image 863
andreaspfr Avatar asked Nov 24 '11 08:11

andreaspfr


1 Answers

That error message also means that you are trying to load a 32bit snapin from a 64bit powershell instance (or vice-versa.) In your case, you need to compile your program to target the correct bitness: x86. AnyCPU will default to the bitness of your machine, which is 64 bit.

like image 156
x0n Avatar answered Oct 20 '22 00:10

x0n