I'm trying to export all computer names from AD to a text file. Currently i have the code below which lists all the computers in the console but i can't figure out how to save them all to a txt. I've got a line
File.WriteAllText(@"results.txt", temp[0].Substring(10));but it only pulls the last line of the console output, not the whole thing.
Any ideas?
Thanks,
Taran.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.DirectoryServices;
using System.IO;
namespace AD
{
class Program
{
static void Main()
{
Console.WriteLine("Enter Domain Name");
string server = Console.ReadLine();
Console.WriteLine("Enter Z UserID");
string adminUser = Console.ReadLine();
Console.WriteLine("Enter Password");
string adminPass = Console.ReadLine();
// Get Building and Floor
Console.WriteLine("Enter Building and Floor)");
string buildFloor = Console.ReadLine();
// Get WS or LT
Console.WriteLine("Workstation or Laptop?");
string wslt = Console.ReadLine();
// Create Computer Name
string compNameSearch = "COMPUTER" + buildFloor + wslt;
Console.WriteLine(compNameSearch);
// Show all AD Computers
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://" + server + "";
de.Username = adminUser;
de.Password = adminPass;
try
{
DirectorySearcher ser = new DirectorySearcher();
ser.Filter = "(&ObjectCategory=computer)"; //Only allows Computers to be returned in results.
SearchResultCollection results = ser.FindAll();
foreach (SearchResult res in results)
{
string[] temp = res.Path.Split(','); //temp[0] would contain the computer name ex: cn=computerName,..
Console.WriteLine(temp[0].Substring(10));//returns everything after LDAP://CN= until end of temp[0].
File.WriteAllText(@"results.txt", temp[0].Substring(10));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
// Display Available Computer Names by showing all combinations of compNameSearch that are not in AD.
finally
{
de.Dispose();//Clean up resources
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}

New Topic/Question
Reply



MultiQuote



|