1

I am trying to restart a VM using powershell in C#.

First i am trying to run the GET-VM command. It is giving an exception at line:

PSSnapInInfo psinfo = runspaceConfig.AddPSSnapIn("System.Management.Automation", out snapEx);

in below given code. Can someone tell me where i am doing it wrong.

Exception Message : No snap-ins have been registered for Windows PowerShell version 2

My Code :

Command command = new Command("Get-VM");
            command.Parameters.Add("Name", "PIE01010299");
            RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();
            PSSnapInException snapEx = null;
            PSSnapInInfo psinfo = runspaceConfig.AddPSSnapIn("System.Management.Automation", out snapEx);
            Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfig);
            runSpace.Open();
            Pipeline pipeline = runSpace.CreatePipeline();

            pipeline.Commands.Add(command);
            Collection<PSObject> output = pipeline.Invoke();
            runSpace.Close();
            foreach (PSObject psObject in output)
            {
               Console.WriteLine(psObject.ToString());
            }

1 Answer 1

1

System.Management.Automation is not a snapin. It is the core PowerShell engine assembly. It is loaded by default because your C# project needs to reference that assembly. You probably want to import the Hyper-V module e.g.:

pipeline.Commands.AddCommand("Import-Module").AddArgument("Hyper-V");
pipeline.Invoke();
pipeline.Clear();

Or use the InitialSessionState.ImportPSModule method and then associate that with the runspace.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.