Searching through Active-Directory on Windows 2008 Server Core R2

Searching through Active-Directory can be done using the DirectorySearcher. First we need to connect to Active-Directory.


PS > $Connection = "LDAP://Server1/DC=APA,DC=CORP"
PS > $AD = [adsi] $Connection

We then create a new object containing the Searcher.


PS > $Searcher = New-Object System.DirectoryServices.DirectorySearcher $AD

In order to search through Active-Directory we have to specify a filter that tells the searcher what kind of information we wnat to look up.
First we define which objectClass we want to search through and then we specify the criterias. First we’ll search for a specicif Group.


PS > $Searcher.Filter = '(&(objectClass=Group)(name=NewGroup))'
PS > $Group = ($Searcher.FindOne()).GetDirectoryEntry()
PS > $Group


distinguishedName : {CN=NewGroup,OU=NewOU,DC=APA,DC=CORP}
Path              : LDAP://Server1/CN=NewGroup,OU=NewOU,DC=APA,DC=CORP

If we instead want to search for All groups we can specify this in the searcher.


PS > $Searcher.Filter = '(objectClass=Group)'
PS > $AllGroups = $Searcher.FindAll()
PS > $AllGroups

Path                                    Properties
----                                    ----------
LDAP://Server1/CN=Administrators,CN=... {admincount, iscriticalsystemobject,...
LDAP://Server1/CN=Users,CN=Builtin,D... {iscriticalsystemobject, samaccountn...
LDAP://Server1/CN=Guests,CN=Builtin,... {iscriticalsystemobject, samaccountn...
LDAP://Server1/CN=Print Operators,CN... {admincount, iscriticalsystemobject,...

We can also present the returned information in a variaty of ways, using ForEach-Object CmdLet.


PS > $AllGroups | ForEach { $_.GetDirectoryEntry() }


distinguishedName : {CN=Administrators,CN=Builtin,DC=APA,DC=CORP}
Path              : LDAP://Server1/CN=Administrators,CN=Builtin,DC=APA,DC=CORP

distinguishedName : {CN=Users,CN=Builtin,DC=APA,DC=CORP}
Path              : LDAP://Server1/CN=Users,CN=Builtin,DC=APA,DC=CORP

distinguishedName : {CN=Guests,CN=Builtin,DC=APA,DC=CORP}
Path              : LDAP://Server1/CN=Guests,CN=Builtin,DC=APA,DC=CORP

distinguishedName : {CN=Print Operators,CN=Builtin,DC=APA,DC=CORP}
Path              : LDAP://Server1/CN=Print Operators,CN=Builtin,DC=APA,DC=CORP

If we instead want to search for a User-Object, we can specify this in the Filter.


PS > $Searcher.Filter = '(&(objectClass=User)(name=jeapic))'
PS > $User = ($Searcher.FindOne()).GetDirectoryEntry()
PS > $User


distinguishedName : {CN=jeapic,OU=NewOU,DC=APA,DC=CORP}
Path              : LDAP://Server1/CN=jeapic,OU=NewOU,DC=APA,DC=CORP

Seraching for all Users is done as shown below


PS > $Searcher.Filter = '(objectClass=User)'
PS > $AllUser = $Searcher.FindAll()
PS > $AllUser

Path                                    Properties
----                                    ----------
LDAP://Server1/CN=Administrator,CN=U... {admincount, logonhours, iscriticals...
LDAP://Server1/CN=Guest,CN=Users,DC=... {iscriticalsystemobject, samaccountn...
LDAP://Server1/CN=SERVER1,OU=Domain ... {primarygroupid, iscriticalsystemobj...
LDAP://Server1/CN=krbtgt,CN=Users,DC... {admincount, countrycode, samaccount...
LDAP://Server1/CN=Client1,CN=Compute... {primarygroupid, iscriticalsystemobj...
LDAP://Server1/CN=SERVER2,CN=Compute... {primarygroupid, iscriticalsystemobj...
LDAP://Server1/CN=jeapic,OU=NewOU,DC... {primarygroupid, mail, displayname, ...

And last, searching for computers in Active-Directory, first we’ll search for one Computer


PS > $Searcher.Filter = '(&(objectClass=Computer)(name=Client1))'
PS > $Computer = ($Searcher.FindOne()).GetDirectoryEntry()
PS > $Computer


distinguishedName : {CN=Client1,CN=Computers,DC=APA,DC=CORP}
Path              : LDAP://Server1/CN=Client1,CN=Computers,DC=APA,DC=CORP

And finally, searching for All Computers.


PS > $Searcher.Filter = '(objectClass=Computer)'
PS > $AllComputer = $Searcher.FindAll()
PS >
PS > $AllComputer

Path                                    Properties
----                                    ----------
LDAP://Server1/CN=SERVER1,OU=Domain ... {primarygroupid, iscriticalsystemobj...
LDAP://Server1/CN=Client1,CN=Compute... {primarygroupid, iscriticalsystemobj...
LDAP://Server1/CN=SERVER2,CN=Compute... {primarygroupid, iscriticalsystemobj...

Below is the code used in this Post


$Connection = "LDAP://Server1/DC=APA,DC=CORP"
$AD = [adsi] $Connection

$Searcher = New-Object System.DirectoryServices.DirectorySearcher $AD
$Searcher.Filter = '(&(objectClass=Group)(name=NewGroup))'

$Group = ($Searcher.FindOne()).GetDirectoryEntry()
$Group

$Searcher.Filter = '(objectClass=Group)'

$AllGroups = $Searcher.FindAll()
$AllGroups | ForEach { $_.GetDirectoryEntry() }

$Searcher.Filter = '(&(objectClass=User)(name=jeapic))'

$User = ($Searcher.FindOne()).GetDirectoryEntry()
$User

$Searcher.Filter = '(objectClass=User)'

$AllUser = $Searcher.FindAll()

$Searcher.Filter = '(&(objectClass=Computer)(name=Client1))'

$Computer = ($Searcher.FindOne()).GetDirectoryEntry()
$Computer

$Searcher.Filter = '(objectClass=Computer)'

$AllComputer = $Searcher.FindAll()
$AllComputer

Rating 3.00 out of 5
[?]

Adding User To Group in Active-Directory on Windows 2008 Server Core R2

To add our new User to our Group, the add() method is used as shown below.


PS > $Connection = "LDAP://Server1/CN=NewGroup,OU=NewOU,DC=APA,DC=CORP"
PS > $Group = [adsi] $Connection
PS > $User = "LDAP://Server1/CN=jeapic,OU=NewOU,DC=APA,DC=CORP"
PS > $Group.Add($User)

If we look at the memebers of the group, our user will be added.


PS > $Group.member

CN=jeapic,OU=NewOU,DC=APA,DC=CORP

In the AD MMC Snapin, we can view the changes that we made.

servercore-08

And if we want to remove a user from a Group we can use the Delete() method.


PS > $Group.Remove($User)

Below is the code used in this post


$Connection = "LDAP://Server1/CN=NewGroup,OU=NewOU,DC=APA,DC=CORP"
$Group = [adsi] $Connection

$User = "LDAP://Server1/CN=jeapic,OU=NewOU,DC=APA,DC=CORP"

$Group.Add($User)

Rating 2.00 out of 5
[?]

Creating a User in Active-Directory on Windows 2008 Server Core R2

Creating a user is basically the same as creating a Group or an OU. First we cast the OU we want to use into a [adsi] object and then start setting the properties. After adding all properties we set a password and set Disabled to false, otherwise the account will be disabled.


PS > $Connection = "LDAP://Server1/OU=NewOU,DC=APA,DC=CORP"
PS > $OU = [adsi] $Connection
PS > $User = $OU.Create("user", "cn=jeapic")
PS > $User.Put("sAMAccountName", "jeapic")
PS > $User.Put("userPrincipalName", "jeapic@apa.corp")
PS > $User.Put("DisplayName", "Jean-Luc Picard")
PS > $User.Put("givenName", "Jean-Luc")
PS > $User.Put("sn", "Picard")
PS > $User.Put("Description", "Captain of the Enterprise")
PS > $User.Put("mail", "picard@enterprise.com")
PS > $User.SetInfo()
PS >
PS > $User.PsBase.Invoke("SetPassword", "Password123")
PS > $User.PsBase.InvokeSet("AccountDisabled", $false)
PS > $User.SetInfo()

If we want to set the account to never expires, we can edit the UserAccountControl


PS > $User.userAccountControl[0] = $User.userAccountControl[0] -bor (65536)
PS > $User.SetInfo()

Now we can check out the properties on our User.


PS > $User | Format-List *


objectClass           : {top, person, organizationalPerson, user}
cn                    : {jeapic}
sn                    : {Picard}
description           : {Captain of the Enterprise}
givenName             : {Jean-Luc}
distinguishedName     : {CN=jeapic,OU=NewOU,DC=APA,DC=CORP}
instanceType          : {4}
whenCreated           : {1/18/2009 12:08:29 AM}
whenChanged           : {1/18/2009 12:08:32 AM}
displayName           : {Jean-Luc Picard}
uSNCreated            : {System.__ComObject}
uSNChanged            : {System.__ComObject}
name                  : {jeapic}
objectGUID            : {77 84 253 130 36 215 146 76 155 38 10 217 57 208 44 45
                        }
userAccountControl    : {66080}
badPwdCount           : {0}
codePage              : {0}
countryCode           : {0}
badPasswordTime       : {System.__ComObject}
lastLogoff            : {System.__ComObject}
lastLogon             : {System.__ComObject}
pwdLastSet            : {System.__ComObject}
primaryGroupID        : {513}
objectSid             : {1 5 0 0 0 0 0 5 21 0 0 0 171 166 141 168 63 138 126 92
                         158 59 183 83 83 4 0 0}
accountExpires        : {System.__ComObject}
logonCount            : {0}
sAMAccountName        : {jeapic}
sAMAccountType        : {805306368}
userPrincipalName     : {jeapic@apa.corp}
objectCategory        : {CN=Person,CN=Schema,CN=Configuration,DC=APA,DC=CORP}
dSCorePropagationData : {1/1/1601 12:00:00 AM}
mail                  : {picard@enterprise.com}
nTSecurityDescriptor  : {System.__ComObject}
AuthenticationType    : Secure
Children              : {}
Guid                  : 4d54fd8224d7924c9b260ad939d02c2d
ObjectSecurity        : System.DirectoryServices.ActiveDirectorySecurity
NativeGuid            : 4d54fd8224d7924c9b260ad939d02c2d
NativeObject          : System.__ComObject
Parent                : LDAP://Server1/OU=NewOU,DC=APA,DC=CORP
Password              :
Path                  : LDAP://Server1/cn=jeapic,OU=NewOU,DC=APA,DC=CORP
Properties            : {objectClass, cn, sn, description...}
SchemaClassName       : user
SchemaEntry           : System.DirectoryServices.DirectoryEntry
UsePropertyCache      : True
Username              :
Options               : {}
Site                  :
Container             :

If we check out the User through the Active-Directory MMC Snapin we can varify that all information added through PowerShell is added.

servercore-07

If we want to Delete a User in Active-Directory, we can use the Delete() method.


PS > $Connection = "LDAP://Server1/OU=NewOU,DC=APA,DC=CORP"
PS > $OU = [adsi] $Connection
PS > $OU.delete(”user”,”CN=UserToDelete”)

Below is the code used in this post


$Connection = "LDAP://Server1/OU=NewOU,DC=APA,DC=CORP"
$OU = [adsi] $Connection
$User = $OU.Create("user", "cn=jeapic")
$User.Put("sAMAccountName", "jeapic")
$User.Put("userPrincipalName", "jeapic@apa.corp")
$User.Put("DisplayName", "Jean-Luc Picard")
$User.Put("givenName", "Jean-Luc")
$User.Put("sn", "Picard")
$User.Put("Description", "Captain of the Enterprise")
$User.Put("mail", "picard@enterprise.com")
$User.SetInfo()

$User.PsBase.Invoke("SetPassword", "Password123")
$User.PsBase.InvokeSet("AccountDisabled", $false)
$User.SetInfo()

$User.userAccountControl[0] = $User.userAccountControl[0] -bor (65536)
$User.SetInfo()

$Connection = "LDAP://Server1/OU=NewOU,DC=APA,DC=CORP"
$OU = [adsi] $Connection
$OU.delete("user", "cn=UserToDelete")

Rating 3.00 out of 5
[?]

Creating a Group in Active-Directory on Windows 2008 Server Core R2

We can create Groups in Active-Directory through PowerShell. Step one is to make a connection to the OU where you want to place your Group. In this example I’ll use the OU that i created in a previous post.


PS > $Connection = "LDAP://OU=NewOU,DC=BPA,DC=CORP"
PS > $OU = [adsi] $Connection
PS > $OU


distinguishedName : {OU=NewOU,DC=APA,DC=CORP}
Path              : LDAP://OU=NewOU,DC=APA,DC=CORP

Next, we use the Create() method to create a New Group.


PS > $Group = $OU.Create("Group", "CN=NewGroup")
PS > $Group.setinfo()

If we look at the group through the MMC snapin.

servercore-05

It’s also possible to retrieve detailed information if we pipe the object to the Format-List CmdLet.


PS > $Group | Format-List *


objectClass           : {top, group}
cn                    : {NewGroup}
distinguishedName     : {CN=NewGroup,OU=NewOU,DC=APA,DC=CORP}
instanceType          : {4}
whenCreated           : {1/17/2009 7:45:09 AM}
whenChanged           : {1/17/2009 7:45:09 AM}
uSNCreated            : {System.__ComObject}
uSNChanged            : {System.__ComObject}
name                  : {NewGroup}
objectGUID            : {54 186 37 137 40 211 36 68 191 63 127 148 134 182 116
                        2}
objectSid             : {1 5 0 0 0 0 0 5 21 0 0 0 171 166 141 168 63 138 126 92
                         158 59 183 83 80 4 0 0}
sAMAccountName        : {$G21000-VS2BCS6RM3JL}
sAMAccountType        : {268435456}
groupType             : {-2147483646}
objectCategory        : {CN=Group,CN=Schema,CN=Configuration,DC=APA,DC=CORP}
dSCorePropagationData : {1/1/1601 12:00:00 AM}
nTSecurityDescriptor  : {System.__ComObject}
AuthenticationType    : Secure
Children              : {}
Guid                  : 36ba258928d32444bf3f7f9486b67402
ObjectSecurity        : System.DirectoryServices.ActiveDirectorySecurity
NativeGuid            : 36ba258928d32444bf3f7f9486b67402
NativeObject          : System.__ComObject
Parent                : LDAP://Server1/OU=NewOU,DC=APA,DC=CORP
Password              :
Path                  : LDAP://Server1/CN=NewGroup,OU=NewOU,DC=APA,DC=CORP
Properties            : {objectClass, cn, distinguishedName, instanceType...}
SchemaClassName       : Group
SchemaEntry           : System.DirectoryServices.DirectoryEntry
UsePropertyCache      : True
Username              :
Options               : {}
Site                  :
Container             :

If we inspect the returned information above, sAMAccountName looks a little funny, changing that is simple through PowerShell.


PS > $Connection = "LDAP://Server1/CN=NewGroup,OU=NewOU,DC=APA,DC=CORP"
PS > $Group = [adsi] $Connection

PS > $Group.put("sAMAccountName", ”NewGroup")
PS > $Group.SetInfo()

PS > $Group.sAMAccountName

NewGroup

It’s also possible to change the property directly as shown below.


PS > $Group.sAMAccountName = "Another Name"
PS > $Group.SetInfo()

Below is the code used in this post


$Connection = "LDAP://OU=NewOU,DC=APA,DC=CORP"
$OU = [adsi] $Connection

$Group = $OU.Create("Group", "CN=NewGroup")
$Group.setinfo()

$Connection = "LDAP://Server1/CN=NewGroup,OU=NewOU,DC=APA,DC=CORP"

$Group = [adsi] $Connection
$Group.put("sAMAccountName", ”NewGroup")
$Group.SetInfo()

$Group.sAMAccountName = "Another Name"
$Group.SetInfo()

Rating 4.00 out of 5
[?]

Creating an OU in Active-Directory on Windows 2008 Server Core R2

When creating Organizational-Units through PowerShell, we can use the Create() method. First we need to connect to the place where we want to create it. In this example I’m going to create an OU in the top level of my domain. If you want to create further down in the structure, simply connect to the level that you wish to create the OU in.


PS > $Connect = "LDAP://Server1/DC=APA,DC=CORP"
PS > $AD = [adsi] $Connect

PS > $OU = $AD.Create("OrganizationalUnit", "OU=NewOU")
PS > $OU.SetInfo()

If we call on our variable $OU, it returns information about the object that we just created.


PS > $OU = [adsi] "LDAP://Server1/OU=NewOU,DC=APA,DC=CORP"
PS > $OU


distinguishedName : {OU=NewOU,DC=APA,DC=CORP}
Path              : LDAP://Server1/OU=NewOU,DC=APA,DC=CORP

And if we look in the Active-Directory snapin, we can see that our new OU is created.

servercore-03

If we want to explore the properties on our Organizational-Unit, we can simply pipe the object to the Format-List CmdLet


PS > $OU | Format-List *


objectClass           : {top, organizationalUnit}
ou                    : {NewOU}
distinguishedName     : {OU=NewOU,DC=APA,DC=CORP}
instanceType          : {4}
whenCreated           : {1/17/2009 7:34:43 AM}
whenChanged           : {1/17/2009 7:34:43 AM}
uSNCreated            : {System.__ComObject}
uSNChanged            : {System.__ComObject}
name                  : {NewOU}
objectGUID            : {169 138 178 239 63 60 113 76 153 251 193 11 61 99 27 1
                        75}
objectCategory        : {CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=A
                        PA,DC=CORP}
dSCorePropagationData : {1/1/1601 12:00:00 AM}
nTSecurityDescriptor  : {System.__ComObject}
AuthenticationType    : Secure
Children              : {}
Guid                  : a98ab2ef3f3c714c99fbc10b3d631baf
ObjectSecurity        : System.DirectoryServices.ActiveDirectorySecurity
NativeGuid            : a98ab2ef3f3c714c99fbc10b3d631baf
NativeObject          : System.__ComObject
Parent                : LDAP://Server1/DC=APA,DC=CORP
Password              :
Path                  : LDAP://Server1/OU=NewOU,DC=APA,DC=CORP
Properties            : {objectClass, ou, distinguishedName, instanceType...}
SchemaClassName       : organizationalUnit
SchemaEntry           : System.DirectoryServices.DirectoryEntry
UsePropertyCache      : True
Username              :
Options               : {}
Site                  :
Container             :

If we want to modify properties, we can use the put() method. In this example we will set the City and the Description of the OU.


PS > $OU.put("l", "Gothenburg")
PS > $OU.put("Description", "www.PowerShell.nu")
PS > $OU.SetInfo()

We can check the values set by calling the Objects Property.


PS > $OU.l

Gothenburg

PS > $OU.Description

www.PowerShell.nu

If we look at the properties on our OU in the Active-Directory snapin we can see the changes.

servercore-04

And last step, removing an Organizational-Unit. It’s possible to accomplish through the deleteTree() method as shown below.


PS > $OU.psbase.deleteTree()

Below is the complete code used in this example:


$Connect = "LDAP://Server1/DC=APA,DC=CORP"
$AD = [adsi] $Connect

$OU = $AD.Create("OrganizationalUnit", "ou=NewOU")
$OU.SetInfo()

$OU.put("l", "Gothenburg")
$OU.put("Description", "www.PowerShell.nu")
$OU.setinfo()

$OU.psbase.deleteTree()

Rating 3.00 out of 5
[?]