6

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

andreaspfr
  • 2,298
  • 5
  • 42
  • 51
  • I'm getting a `Cannot load Windows PowerShell snap-in Microsoft.Exchange.Management.PowerShell.E2010 because of the following error: The type initializer for 'Microsoft.Exchange.Data.Directory.Globals' threw an exception.` has anyone encountered that? – BRogers Jun 19 '13 at 17:49
  • Ask a new question, @BRogers - this is not the right place. – x0n Jun 21 '13 at 14:46

2 Answers2

5

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.

x0n
  • 51,312
  • 7
  • 89
  • 111
  • When I switch it to x86 I get `Could not load file or assembly 'MyProject' or one of its dependencies. An attempt was made to load a program with an incorrect format. ` using VS2010. Any suggestions? – BRogers Jun 19 '13 at 18:28
1

I had a similar issue... I was trying to execute a custom powershell cmdlet from a console application. I verified that my console is set to 4.0 framework and the powershell was 3.0. It turned out that the issue was "prefer 32 bit" setting in bild tab of the console was set to true. I unchecked it and everything worked!

user1019042
  • 2,428
  • 9
  • 43
  • 85