Thursday, September 20, 2012

Listing all hosts in Active Directory using PowerShell

PowerShell is now a mature scripting language. I've enjoyed watching it flourish from it's early conception and the many ways in which people were convinced that it was better than Perl, or the Unix KornShell.  Well for Windows that is definitely the case as it puts the operating system in the league of serious enterprise systems especially now Server Core comes with the .Net framework and PowerShell making the command line offering more attractive than it's earlier attempt.  There are some great features that PowerShell provides which make it an enterprise suitable automation language, such as the ability to interact with WMI for remote and local host manipulation and ADSI for automating your Active Directory tasks.  Why would you want to click another mouse button, apart from to launch your PowerShell script to update 1000s of hosts, or change a particular aspect of all 5 million users in your enterpirse?  Clicking is for wimps, that's those of you who still like Windows Icons Menus and Pointers :-)

One thing I found great the other day was how simple and easy it is to get a list of all the properties from your hosts registered in Active Directory in so few lines;

$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'LDAP://CN=Computers,DC=xx,DC=xxxx')


foreach ($hostObject in $DirSearcher.FindAll())
{
        echo $hostObject.Properties;    # Will list all hosts and their AD properties
        # echo $hostObject.Properties.name; # List just the hostname, dnshostname for FQDN name
}

If you simply want to grab a particular object from the directory you only need do the following;
$AD=[adsi]’LDAP://CN=xxxx,OU=xxxx,OU=xxx,DC=xxxx,DC=xxxx’
$AD.Properties


Couldn't be simpler.  And as long as the object has methods you can perform various actions to update values and more.