Active Directory Users and Computers






4.94/5 (15 votes)
Display Active Directory users and computers and export them to CSV or Excel document
- Download Active Directory Information (source) - 1.1 MB
- Download Active Directory Information (source noexe) - 376.6 KB
- Download Active Directory Information (EXE) - 349.5 KB
- Download Active Directory Information Console (source) - 35.3 KB
- Download Active Directory Information Console (source noexe) - 12.1 KB
- Download Active Directory Information Console (EXE) - 4.9 KB
Introduction
This article explains how to find users and computers in your domain and display all the information about them which have been saved in active directory and export the results to CSV or Excel file.
Background
If you have Windows Server, you can view all users in your domain by adding active directory role or its features. But if you don't use Windows Server and you are a member of a domain, just download ActiveDirectoryInformation.exe from the top of this page and run the application on your computer. All users and computers and their information will be displayed by using System.DirectoryServices.AccountManagement
namespace and you can save results in Excel format. You can use this application even if you are not a domain admin.
Using the Code
We use System.DirectoryServices.AccountManagement
namespace for working with active directory. To use this namespace, you should add System.DirectoryServices.AccountManagement
to your project references.
To find users in active directory, first we should find domain name. This code returns domain name:
string stringDomainName =
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
Then we specify which information we want to save about each user and computer. As you can see in the code below, we define User
class properties of user. Now we initialize User
constructor which has eight arguments and save input data in User’s properties. We also define properties function which returns all saved properties of User
.
public class User
{
public String SamAccountName { get; set; }
public String DisplayName { get; set; }
public String Name { get; set; }
public String GivenName { get; set; }
public String Surname { get; set; }
public String Description { get; set; }
public Boolean? Enabled { get; set; }
public DateTime? LastLogon { get; set; }
public User(String SamAccountName, String DisplayName, String Name,
String GivenName, String Surname, String Description,
Boolean? Enabled, DateTime? LastLogon)
{
this.SamAccountName = SamAccountName;
this.DisplayName = DisplayName;
this.Name = Name;
this.GivenName = GivenName;
this.Surname = Surname;
this.Description = Description;
this.Enabled = Enabled;
this.LastLogon = LastLogon;
}
public List<string> Properties()
{
return new List<string> { SamAccountName, DisplayName, Name,
GivenName, Surname, Description, Enabled.ToString(), LastLogon.ToString() };
}
public int UserPropertiesTotal = 8;
public static string[] StringArrayUesrProperties = { "SamAccountName",
"DisplayName", "Name", "GivenName", "Surname",
"Description", "Enabled", "LastLogon" };
}
We also make a list of users which saves information about all users:
public Users Users1 = new Users();
public class Users : List<User> { }
We do the same for computers too. First, we make a computer
class and a list of all computers.
public Computers Computers1 = new Computers();
public class Computers : List<Computer> { }
public class Computer
{
public String SamAccountName { get; set; }
public String DisplayName { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public Boolean? Enabled { get; set; }
public DateTime? LastLogon { get; set; }
public Computer(String SamAccountName,
String DisplayName, String Name, String Description,
Boolean? Enabled, DateTime? LastLogon)
{
this.SamAccountName = SamAccountName;
this.DisplayName = DisplayName;
this.Name = Name;
this.Description = Description;
this.Enabled = Enabled;
this.LastLogon = LastLogon;
}
public List<string> Properties()
{
return new List<string> { SamAccountName, DisplayName,
Name, Description, Enabled.ToString(), LastLogon.ToString() };
}
public int UserPropertiesTotal = 6;
public static string[] StringArrayComputerProperties = { "SamAccountName",
"DisplayName", "Name", "Description", "Enabled", "LastLogon" };
}
After running the application, if user just clicks on Show button, then all users will be displayed. In this state after finding domain name, we use these classes:
- Initialize an instance of
PrincipalContext
which refers to that domain UserPrincipal
for all userPrincipalSearcher
to find each user inuserPrincipal
. In this example, we want to return all users so we usesearch.FindAll()
.
Now, we can search through all users and save those we want. If you don’t select any group or password in application interface, then all users will be displayed in DataGrid
.
private void ShowUsers()
{
//Check password
Boolean boolPass;
//Check groups
Boolean boolGroup;
Users1.Clear();
int intCounter = 0;
PrincipalContext PrincipalContext1 =
new PrincipalContext(ContextType.Domain, stringDomainName);
UserPrincipal UserPrincipal1 = new UserPrincipal(PrincipalContext1);
PrincipalSearcher search = new PrincipalSearcher(UserPrincipal1);
foreach (UserPrincipal result in search.FindAll())
{
//Check default pass
if (checkBoxPass.IsChecked == true)
{
if (PrincipalContext1.ValidateCredentials
(result.SamAccountName, PasswordBoxPass.Password))
{
boolPass = true;
}
else
{
boolPass = false;
}
}
else
{
boolPass = true;
}
//Check group
if (comboBoxGroups.SelectedIndex >= 0)
{
PrincipalSearchResult<Principal> PrincipalSearchResults1 = result.GetGroups();
foreach (Principal PrincipalSearchResult1 in PrincipalSearchResults1)
{
if (PrincipalSearchResult1.Name == comboBoxGroups.SelectedValue.ToString())
{
boolGroup = true;
break;
}
}
}
else
{
boolGroup = true;
}
//Add user
if (boolPass && boolGroup)
{
User User1 = new User(result.SamAccountName, result.DisplayName,
result.Name, result.GivenName, result.Surname,
result.Description, result.Enabled, result.LastLogon);
Users1.Add(User1);
intCounter++;
}
}
search.Dispose();
datagridResult.ItemsSource = Users1;
datagridResult.Items.Refresh();
MessageBox.Show(intCounter + " users. ");
EnumDataGrid1 = EunmDataGrid.users;
}
Sometimes, you want to display users from specific groups, for example, domain admins. In this situation, you can select that group. Also, if you enter a password, then only users who have the same password will be displayed.
To find all computers, we use the same method, but instead of UserPrincipal
, we use ComputerPrincipal
and also we don’t need to check passwords or groups.
private void ShowComputers()
{
Computers1.Clear();
int intCounter = 0;
PrincipalContext PrincipalContext1 =
new PrincipalContext(ContextType.Domain, stringDomainName);
ComputerPrincipal ComputerPrincipal1 = new ComputerPrincipal(PrincipalContext1);
PrincipalSearcher search = new PrincipalSearcher(ComputerPrincipal1);
foreach (ComputerPrincipal result in search.FindAll())
{
Computer Computer1 = new Computer(result.SamAccountName, result.DisplayName,
result.Name, result.Description, result.Enabled, result.LastLogon);
Computers1.Add(Computer1);
intCounter++;
}
search.Dispose();
datagridResult.ItemsSource = Computers1;
datagridResult.Items.Refresh();
MessageBox.Show(intCounter + " computers. ");
EnumDataGrid1 = EunmDataGrid.computers;
}
Now by pressing show button, all information about all users or computers in active directory of your domain will be shown in DataGrid
.
private void buttonShow_Click(object sender, RoutedEventArgs e)
{
try
{
if (stringDomainName != null)
{
datagridResult.ItemsSource = null;
if (radiobuttonUsers.IsChecked == true)
{
ShowUsers();
}
else if (radiobuttonComputers.IsChecked == true)
{
ShowComputers();
}
}
else
{
MessageBox.Show("Your computer is not a member of domain",
"Active Directory Users", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
Export Result to CSV
We define two functions to export results to CSV. First one for exporting users
and second one for exporting computers
. Both functions are the same and their only difference is the type of data which that function will save.
private void ExportUserstoCSV(string stringFileName)
{
// File FileStream1 = new System.IO.File();
StringBuilder StringBuilder1 = new StringBuilder(null);
foreach (string string1 in User.StringArrayUesrProperties)
{
if (StringBuilder1.Length == 0)
StringBuilder1.Append(string1);
StringBuilder1.Append(',' + string1);
}
StringBuilder1.AppendLine();
foreach (User User1 in Users1)
{
StringBuilder StringBuilderTemp = new StringBuilder(null);
foreach (string string1 in User1.Properties())
{
if (StringBuilderTemp.Length == 0)
StringBuilderTemp.Append(string1);
StringBuilderTemp.Append(',' + string1);
}
// StringBuilder1.AppendLine();
StringBuilder1.AppendLine(StringBuilderTemp.ToString());
}
File.WriteAllText(stringFileName, StringBuilder1.ToString(), Encoding.UTF8);
MessageBox.Show("Saved Successfully", "Active Directory",
MessageBoxButton.OK, MessageBoxImage.Information);
}
Export computers
to CSV:
private void ExportComputerstoCSV(string stringFileName)
{
// File FileStream1 = new System.IO.File();
StringBuilder StringBuilder1 = new StringBuilder(null);
foreach (string string1 in Computer.StringArrayComputerProperties)
{
if (StringBuilder1.Length == 0)
StringBuilder1.Append(string1);
StringBuilder1.Append(',' + string1);
}
StringBuilder1.AppendLine();
foreach (Computer Computer1 in Computers1)
{
StringBuilder StringBuilderTemp = new StringBuilder(null);
foreach (string string1 in Computer1.Properties())
{
if (StringBuilderTemp.Length == 0)
StringBuilderTemp.Append(string1);
StringBuilderTemp.Append(',' + string1);
}
// StringBuilder1.AppendLine();
StringBuilder1.AppendLine(StringBuilderTemp.ToString());
}
File.WriteAllText(stringFileName, StringBuilder1.ToString(), Encoding.UTF8);
MessageBox.Show("Saved Successfully", "Active Directory",
MessageBoxButton.OK, MessageBoxImage.Information);
}
Export Result to Excel
We can also save the results in other formats. In this part, we export results to Excel. We use the following function to convert users data to Excel document. There are three foreach
in this function. In the first one, name of properties will be saved in the first row of Excel d. Then in the next two ones, for each user, all its properties will be written to Excel document. Finally, the Excel document will be saved.
private void ExportUserstoExcel(string stringFileName)
{
Excel._Application ExcelApplication;
Excel.Workbook ExcelWorkbook;
Excel.Worksheet ExcelWorksheet;
object objectMisValue = System.Reflection.Missing.Value;
Excel.Range ExcelRangeCellinstance;
ExcelApplication = new Excel.Application();
ExcelWorkbook = ExcelApplication.Workbooks.Add(objectMisValue);
ExcelWorksheet = (Excel.Worksheet)ExcelWorkbook.Worksheets.get_Item(1);
ExcelApplication.DisplayAlerts = false;
ExcelRangeCellinstance = ExcelWorksheet.get_Range("A1", Type.Missing);
int intRow = 1;
int intColumn = 1;
foreach (string string1 in User.StringArrayUesrProperties)
{
ExcelWorksheet.Cells[intRow, intColumn] = string1;
intColumn++;
}
intRow++;
foreach (User User1 in Users1)
{
intColumn = 1;
foreach (string string1 in User1.Properties())
{
ExcelWorksheet.Cells[intRow, intColumn] = string1;
intColumn++;
}
intRow++;
}
//Highlight first row
Excel.Range ExcelRange1 = ExcelWorksheet.get_Range("A1", Type.Missing);
ExcelRange1.EntireRow.Font.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
ExcelRange1.Interior.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSkyBlue);
ExcelRange1.EntireRow.Font.Size = 14;
ExcelRange1.EntireRow.AutoFit();
//Save Excel
ExcelWorkbook.SaveAs(stringFileName, Excel.XlFileFormat.xlWorkbookNormal,
objectMisValue, objectMisValue, objectMisValue, objectMisValue,
Excel.XlSaveAsAccessMode.xlExclusive, objectMisValue,
objectMisValue, objectMisValue, objectMisValue, objectMisValue);
ExcelWorkbook.Close();
MessageBox.Show("Saved Successfully",
"Active Directory", MessageBoxButton.OK, MessageBoxImage.Information);
}
Export computers to Excel:
private void ExportComputerstoExcel(string stringFileName)
{
Excel._Application ExcelApplication;
Excel.Workbook ExcelWorkbook;
Excel.Worksheet ExcelWorksheet;
object objectMisValue = System.Reflection.Missing.Value;
Excel.Range ExcelRangeCellinstance;
ExcelApplication = new Excel.Application();
ExcelWorkbook = ExcelApplication.Workbooks.Add(objectMisValue);
ExcelWorksheet = (Excel.Worksheet)ExcelWorkbook.Worksheets.get_Item(1);
ExcelApplication.DisplayAlerts = false;
ExcelRangeCellinstance = ExcelWorksheet.get_Range("A1", Type.Missing);
int intRow = 1;
int intColumn = 1;
foreach (string string1 in Computer.StringArrayComputerProperties)
{
ExcelWorksheet.Cells[intRow, intColumn] = string1;
intColumn++;
}
intRow++;
foreach (Computer Computer1 in Computers1)
{
intColumn = 1;
foreach (string string1 in Computer1.Properties())
{
ExcelWorksheet.Cells[intRow, intColumn] = string1;
intColumn++;
}
intRow++;
}
//Highlight first row
Excel.Range ExcelRange1 = ExcelWorksheet.get_Range("A1", Type.Missing);
ExcelRange1.EntireRow.Font.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
ExcelRange1.Interior.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSkyBlue);
ExcelRange1.EntireRow.Font.Size = 14;
ExcelRange1.EntireRow.AutoFit();
//Save Excel
ExcelWorkbook.SaveAs(stringFileName, Excel.XlFileFormat.xlWorkbookNormal, objectMisValue,
objectMisValue, objectMisValue, objectMisValue, Excel.XlSaveAsAccessMode.xlExclusive,
objectMisValue, objectMisValue, objectMisValue, objectMisValue, objectMisValue);
ExcelWorkbook.Close();
MessageBox.Show("Saved Successfully", "Active Directory",
MessageBoxButton.OK, MessageBoxImage.Information);
}
We add this code to export button so when user clicks on it, save dialog box will be displayed and if user decided to save the result, we send that file name to ExportExcell
function.
public void buttonExport_Click(object sender, RoutedEventArgs e)
{
try
{
if (EnumDataGrid1 != EunmDataGrid.empty)
{
if (radiobuttonExcel.IsChecked == true)
{
Microsoft.Win32.SaveFileDialog SaveFileDialog1 =
new Microsoft.Win32.SaveFileDialog();
SaveFileDialog1.Filter = "Excel Workbook (*.xls)|*.xls";
if ((bool)SaveFileDialog1.ShowDialog())
{
if (EnumDataGrid1 == EunmDataGrid.users)
{
ExportUserstoExcel(SaveFileDialog1.FileName);
}
else if (EnumDataGrid1 == EunmDataGrid.computers)
{
ExportComputerstoExcel(SaveFileDialog1.FileName);
}
}
}
else
{
Microsoft.Win32.SaveFileDialog SaveFileDialog1 =
new Microsoft.Win32.SaveFileDialog();
SaveFileDialog1.Filter = "Comma-Separated Value (*.csv)|*.
<span id="frmark_1" style="color: " +
"white; font-weight: bold; background-color: highlight;">
<span id="frmark_1" style="color: white; " +
"font-weight: bold; background-color: highlight;">csv</span></span>";
if ((bool)SaveFileDialog1.ShowDialog())
{
if (EnumDataGrid1 == EunmDataGrid.users)
{
ExportUserstoCSV(SaveFileDialog1.FileName);
}
else if (EnumDataGrid1 == EunmDataGrid.computers)
{
ExportComputerstoCSV(SaveFileDialog1.FileName);
}
}
}
}
else
{
MessageBox.Show("First click on show button",
"Active Directory Users", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Points of Interest
Display everything about users and computers in your domain with just a click.
History
- 26th January, 2013: Initial version