Wednesday, August 11, 2010

C# Script to list local users and disabled status on Windows Servers

The following script will list all local users and their disabled status on each of the windows servers that you put into the "servers" array variable. This code is written in C# and you will need to include the System.DirectoryServices assembly.


using System;
using System.DirectoryServices;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] servers = { "ServerName1", "ServerName2", "ServerName3" };
            DirectoryEntry de = new DirectoryEntry();

            foreach (string server in servers)
            {
                de.Path = "WinNT://" + server + ",computer";

                Console.WriteLine("Server: " + server);
                foreach (DirectoryEntry d in de.Children)
                {
                    if (d.SchemaClassName == "User")
                    {
                        int userFlags = (int)d.Properties["UserFlags"].Value;
                        bool disabled = (userFlags & 2) == 2;
                        string name = (string)d.Properties["Name"].Value;
                        Console.WriteLine(name + " (" + disabled + ")");
                    }
                }
                Console.WriteLine();
            }
           
            Console.ReadLine();
        }
    }
}
 

No comments:

Post a Comment