Always A-HEAD, By being ahead you are always master of time

Hits

BOOKS

Thursday, February 08, 2007

Managing groups in Active Directory with Powershell

Let's do something with groups in Active directory, I have couple of users and one group under OU named Singapore. My intention here is to modify only user accounts and not group so I have condition them with SamAccountType.

$SNGOU=new-object directoryservices.directoryentry("LDAP://ou=singapore,DC=zarays,dc=com") # Let's connect to OU name Singapore
$UserObject=$sngou.psbase.Children # Lets get the object under OU

foreach($user in $userobject) {
if ($user.sAMAccountType -eq 805306368) { # we want to just update user object and not group object
$user.put("Description","Storage Admins") # We change the description to Storage Admins
$user.setinfo() # Commit changes
}
}


Let's create a group in Singapore OU :

$SNGOU=new-object directoryservices.directoryentry("ldap://ou=singapore,DC=zarays,dc=com/") # Let's connect to OU name Singapore
$Grp=$SNGOU.psbase.Children.Add("CN=Storageadmins","group")

$grp.psbase.commitchanges()

Group is created. Now lets add member to this group. Assuming there are several users in OU, we will only add user whose department is Provisioning. But before I go to the code, I would like to share something with you. You won't see member property if you do

$Grp | gm

or $grp.member

cause there is nothing to display but moment you add user, the next moment you do

$grp | gm

you will see member property.

If you are as beginner like me & would like to know the property, simplest way is to use google. After searching 4 hours I got to know Oh what is happening. And similiarly there is attribute called managedby, it is also having same story. There might be many.

$grp.managedBy.Value

$grp.managedBy.Add("CN=Preetam,OU=Singapore,DC=Zarays,DC=com")

$grp.psbase.CommitChanges()

Let's get to adding members to the group. Remember one thing if your CN name has space you will have to use quotes [$grp.member.add("$DN")].

Also you need a distinguished name in order to add it to any particular group, which is quite logical cause it confirms user object is present and where is it.

$Grp=new-object directoryservices.directoryentry("LDAP://cn=storageadmins,ou=singapore,dc=zarays,dc=com") # GRP -Connection
$SNGOU=new-object directoryservices.directoryentry("
LDAP://ou=singapore,DC=zarays,dc=com") #OU -Connection
$UserObject=$sngou.psbase.Children
# Populate childs in OU

foreach($user in $userobject) {
$DN=$user.distinguishedName
# Get there distinguished name
if ($user.department -eq "Provisioning") {
$grp.member.add("$DN")
#Add them to group

$grp.setinfo() # Commit changes

}
}

There is very good post available on http://janssenjones.typepad.com/, I liked it very much for adding members to the group.

Again there is very very stuff on internet but this cooked by me and I always like to eat that way. And my experience hopefully will help you all.

No comments: