List All Servers in SharePoint Farm - C#


Some times we need to login to all the servers in SharePoint farm just to restart selected Application or Site Pool. Let's see a C# code how to retrieve and recycle selected pools from all the servers in our SharePoint farm.

In this series will see How to retrieve all servers in SharePoint farm using C#

PS: Please check the NOTE at the very end on this post.

First things first import dll's

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Web.Administration;

Declare global variables

    // Global enum Variables
    public enum Action { Start, Stop, Invalid };
    public enum PoolType { AppPool, SitePool };

    // Global Server variable
    public List<string> servers = null;

    // Global Pool's collection variables
    public List<ApplicationPool> appPoolCollection = null;
    public List<Site> siteCollection = null;

Get All SharePoint Farm server names

public void LoadFarmServers(string url, out string message)
{
    SPSecurity.RunWithElevatedPrivileges(delegate ()
    {
        try
        {
            using (SPSite oSite = new SPSite(url))
            {
                servers = new List<string>();
                foreach (SPServer serverInstance in oSite.WebApplication.Farm.Servers)
                {
                    try
                    {
                        // Get only WFE and App Server
                        if ((serverInstance.Role == SPServerRole.WebFrontEnd || serverInstance.Role == SPServerRole.Application))
                        {
                            servers.Add(serverInstance.Name);
                        }
                    }
                    catch (Exception ex)
                    {
                        message = ex.Message;
                    }
                }
            }
        }
        catch (Exception x)
        {
            message = x.Message;
        }

    });
}

🔔⏳🔶🔷 Note 🔷🔶⏳🔔

Have to host this solution as a website in IIS with the same Identity or Service Account used by SharePoint Application/Site Pools and host it in any one of the server in SharePoint farm

We will see how to Start/Stop/Recycle IIS Application Pool and SitePool in the next series.


Related Articles:

-Ratsub

Comments

Post a Comment

Enter your comments..

Popular posts from this blog

People picker Control in PowerApps

Secure When a HTTP request is received Power Automate a.k.a MS Flow

Upload attachment to SharePoint list item using Microsoft Flow

Modern page provisioning using page template

REST call returns XML instead of JSON in SharePoint

HTML field & Date Time formatting in powerapps

Step-By-Step Azure AD App Registration

Approval and auto escalation with time out in Microsoft Flow

Create and configure custom connectors for PowerApps and MSFlow from AzureFunctions

Developing custom reusable components in PowerApps