Search code examples
c#powershellsystem.management

Execute Service fabric cmdlets in c# code


I followed the http://jeffmurr.com/blog/?p=142 for calling powershell scripts from C#. But I am getting error like

The term 'Connect-ServiceFabricCluster' 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.

How to do make it a success.

Posted below is the code i tried. I am passing the value for commands text box as Connect-ServiceFabricCluster -ConnectionEndpoint "localhost:19000" "

 public void DeployMicroservices()
        {
            string result = string.Empty;
            ResultBox.Text = string.Empty;

            // Initialize PowerShell engine
            var shell = PowerShell.Create();

            // Add the script to the PowerShell object
            //shell.Commands.AddScript(Server.MapPath("~")+"Powershell\\microservice.ps1");

            shell.Commands.AddScript(commands.Text);
            // Execute the script
            var results = shell.Invoke();

            if (shell.Streams.Error.Count > 0)
            {
                var builder = new StringBuilder();
                foreach (var error in shell.Streams.Error )
                {
                    builder.Append(error.ToString() + "\r\n");
                }
                ResultBox.Text = Server.HtmlEncode(builder.ToString());
            }

            // display results, with BaseObject converted to string
            // Note : use |out-string for console-like output
            if (results.Count > 0)
            {
                // We use a string builder ton create our result text
                var builder = new StringBuilder();

                foreach (var psObject in results)
                {
                    // Convert the Base Object to a string and append it to the string builder.
                    // Add \r\n for line breaks
                    builder.Append(psObject.BaseObject.ToString() + "\r\n");
                }

                // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
                ResultBox.Text = Server.HtmlEncode(builder.ToString());

            }
        }

My ultimate aim to create a site from where i could deploy the application to the cluster. Or else I have to log in to the system where SF is installed and execute the power shell commands manually.


Solution

  • Ok I found the soultion. The probelm is becasue since my app is running in 32 bit mode the service fabric cmdlets are not loaded. I converetd my app to 64 bit and now the cmdlets like

    Connect-ServiceFabricCluster -ConnectionEndpoint "localhost:19000"  
    

    are identified.