65.9K
CodeProject 正在变化。 阅读更多。
Home

Active Directory 用户和计算机

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.94/5 (15投票s)

2012年11月6日

CPOL

3分钟阅读

viewsIcon

90100

downloadIcon

12331

显示 Active Directory 用户和计算机,并导出到 CSV 或 Excel 文件

引言

本文介绍了如何在您的域中查找用户和计算机,并显示有关它们的在活动目录中保存的所有信息,并将结果导出到 CSV 或 Excel 文件。

背景

如果您有 Windows Server,您可以通过添加活动目录角色或其功能来查看域中的所有用户。但是,如果您不使用 Windows Server 并且您是域的成员,只需从本页顶部下载 ActiveDirectoryInformation.exe 并在您的计算机上运行该应用程序。所有用户和计算机及其信息将通过使用 System.DirectoryServices.AccountManagement 命名空间显示,并且您可以将结果保存为 Excel 格式。即使您不是域管理员,也可以使用此应用程序。

Using the Code

我们使用 System.DirectoryServices.AccountManagement 命名空间来处理活动目录。要使用此命名空间,您应该将 System.DirectoryServices.AccountManagement 添加到您的项目引用中。

要在活动目录中查找用户,首先我们应该找到域名。此代码返回域名。

string stringDomainName = 
  System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

然后我们指定要保存的关于每个用户和计算机的信息。正如您在下面的代码中看到的,我们定义了 User 类的用户属性。现在我们初始化 User 构造函数,该构造函数有八个参数,并将输入数据保存在 User 的属性中。我们还定义了返回 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" };
}

我们还制作了一个用户列表,用于保存所有用户的信息

public Users Users1 = new Users();
public class Users : List<User> { }

我们也对计算机做同样的事情。首先,我们制作一个 computer 类和一个包含所有计算机的列表。

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" };
}

运行应用程序后,如果用户只点击 Show 按钮,则将显示所有用户。在这种状态下,在找到域名后,我们使用这些类

  1. 初始化一个 PrincipalContext 实例,该实例引用该域
  2. UserPrincipal 用于所有用户
  3. PrincipalSearcher 用于在 userPrincipal 中查找每个用户。在此示例中,我们希望返回所有用户,因此我们使用 search.FindAll()

现在,我们可以搜索所有用户并保存我们想要的那些用户。如果您在应用程序界面中没有选择任何组或密码,那么所有用户都将显示在 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;
}

有时,您希望显示来自特定组的用户,例如域管理员。在这种情况下,您可以选择该组。此外,如果您输入密码,那么只有具有相同密码的用户才会被显示。

要查找所有计算机,我们使用相同的方法,但我们使用 ComputerPrincipal 代替 UserPrincipal,并且我们也不需要检查密码或组。

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;
}

现在,通过按下显示按钮,您的域的活动目录中的所有用户或计算机的所有信息都将显示在 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);
    }
}

将结果导出到 CSV

我们定义了两个函数来将结果导出到 CSV。第一个用于导出 users,第二个用于导出 computers。这两个函数是相同的,它们唯一的区别是该函数将保存的数据类型。

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);
}

computers 导出到 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);
}

将结果导出到 Excel

我们还可以将结果保存为其他格式。在这一部分,我们将结果导出到 Excel。我们使用以下函数将用户数据转换为 Excel 文档。此函数中有三个 foreach。在第一个中,属性名称将保存在 Excel 的第一行。然后在接下来的两个中,对于每个用户,其所有属性都将写入 Excel 文档。最后,Excel 文档将被保存。

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);
}

将计算机导出到 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);
}

我们将此代码添加到导出按钮,因此当用户单击它时,将显示保存对话框,并且如果用户决定保存结果,我们将该文件名发送到 ExportExcell 函数。

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());
    }
}

关注点

只需单击一下,即可显示您域中有关用户和计算机的所有信息。

历史

  • 2013 年 1 月 26 日:初始版本
© . All rights reserved.