Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running PowerShell cmdlets in C#

I need to run powershell cmdlets using C# in Visual Studio Console.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Threading;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        private static string RunScript()
        {

            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.Open();
            Pipeline pipeline = runSpace.CreatePipeline();
            Command cmd = new Command("Connect-MsolService"); 
            pipeline.Commands.Add(cmd);
            ICollection results = pipeline.Invoke();  // Here exception occurs
            runSpace.Close();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            return stringBuilder.ToString();
        }




        static void Main(string[] args)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                Console.WriteLine(RunScript());
                Console.ReadKey();
            }
        }
    }
}

When I run the code an Exception occurs:

The term 'Connect-MsolService' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Even though it works when I run the commands in Powershell.

like image 327
saravanan ks Avatar asked Jun 28 '18 10:06

saravanan ks


People also ask

How do I run cmdlets?

Run an old-fashioned command line (cmd.exe), type powershell and execute. Or, you can hit the PowerShell icon on the taskbar. Either way, you'll get a ready-to-use Windows PowerShell console. Use “Get-Help” cmdlet from before as a starting point for your journey.

Can I run PowerShell commands on remote computer?

Windows PowerShell Remoting. Using the WS-Management protocol, Windows PowerShell remoting lets you run any Windows PowerShell command on one or more remote computers. You can establish persistent connections, start interactive sessions, and run scripts on remote computers.


2 Answers

Try to use PowerShell instance, like this:

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new[] { "MSOnline" });
iss.LanguageMode = PSLanguageMode.FullLanguage;
var _o365Runspace = RunspaceFactory.CreateRunspace(iss);
_o365Runspace.Open();
var _o365Shell = PowerShell.Create();
_o365Shell.Runspace = _o365Runspace;
var connect = new Command("Connect-MsolService");
connect.Parameters.Add("Credential", new PSCredential("logon@name",
        GetSecureString("Password"));
_o365Shell.Commands.AddCommand(connect);
// add some msol commands to _o365Shell.Commands as well
_o365Shell.Invoke();
like image 103
thezar Avatar answered Sep 30 '22 22:09

thezar


You are executing it as a CMD command, not as a powershell command. You have to execute it over an Powershell instance. Check executing-powershell-scripts-from-c.

like image 35
Afonso Avatar answered Sep 30 '22 22:09

Afonso