How to add PowerShell SnapIn in C #

I have a Powershell Script that is stored in a line called "script" with the contents:

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 Script manually and add a snap, it works fine

+6
source share
2 answers

This error message also means that you are trying to load a 32-bit snapin from a 64-bit powershell instance (or vice versa). In your case, you need to compile your program for targeted correctness: x86. AnyCPU will be the default bits of your computer, which is 64 bits.

+5
source

I had a similar problem ... I tried to execute a special powershell cmdlet from a console application. I confirmed that my console is installed in the 4.0 framework and powershell is 3.0. It turned out that the problem was the β€œpreferred 32-bit” setting on the bild tab on the console was set to true. I unchecked the box and it worked!

+1
source

Source: https://habr.com/ru/post/902282/


All Articles