Saturday, February 19, 2011

Powershell: Connect to Active Directory

Here is a Powershell script to determine domain membership and then connect to the domain in order to run further commands. Fortunately there is an easier way in Windows Server 2008 R2 by launching Powershell with the Active Directory module. You can then use commands such as New-ADGroup.

Here it is though - a script that does not require the AD module....

#Determine Domain Name
$ObjReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', ‘.’)
$ObjRegKey = $ObjReg.OpenSubKey("SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters")
$DomName = $ObjRegKey.GetValue("Domain")
$domaincnformat = “”
foreach ($comp in $fqdncomponents) {$domaincnformat = $domaincnformat + ‘dc=’ + $comp + ‘,’}
$domaincnformat = $domaincnformat.substring(0,$domaincnformat.length-1)
#Connect to Active Directory
$domain = [ADSI] “LDAP://dc=$domaincnformat”

$OU = "TestOU"

$CreateOU = $domain.Create(“OrganizationalUnit”,”ou=” + $object.OU)

No comments:

Post a Comment