Chapter 26. Active Directory

Introduction

By far, the one thing that makes system administration on the Windows platform most unique is its interaction with Active Directory. As the centralized authorization, authentication, and information store for Windows networks, Active Directory automation forms the core of many enterprise administration tasks.

1 comment

  1. Jerome L Cruz Posted 17 days and 18 hours ago

    Reviewing this chapter first

Add a comment

In PowerShell version one, the primary way to interact with Active Directory came through its support for Active Directory Service Interface (ADSI) type shortcuts.

2 comments

  1. Jerome L Cruz Posted 17 days and 19 hours ago

    Probably should (ADSI) instead of "..(ASI)..." You might also say "...shortcuts using strongly typed [ADSI]var_name objects."

  2. Jerome L Cruz Posted 17 days and 19 hours ago

    or "...[adsi] type accelerator...." as you used in the first book.

Add a comment

In the timeframe of PowerShell version two, the Active Directory team now has an immensely feature-filled PowerShell module to manage Active Directory domains. The Active Directory module includes a PowerShell provider (Set-Location AD:\), and almost one hundred task-specific PowerShell cmdlets.

2 comments

  1. Aleksandar Nikolic Posted 14 days ago

    provider (Set-Location AD:,) and --> provider (Set-Location AD:), and

  2. Aleksandar Nikolic Posted 13 days and 20 hours ago

    backslash is missing again in the comment :(

Add a comment

Working with the Active Directory module comes in two steps.

  1. Support from the server. This module works with any domain that has enabled the Active Directory Web Services feature. Windows Server 2008 R2 enables this feature by default on Active Directory instances, and you can install it on any recent server operating system: from Windows Server 2003 on.

    2 comments

    1. Jerome L Cruz Posted 17 days and 19 hours ago

      Don't need the comma ..." instances and you...". Also "...from Windows Server 2003 R2 on."

    2. Lee Holmes Posted 15 days ago

      Thanks. They actually offer a separate download for 2003 SP2 - it doesn't require R2!

    Add a comment

  2. Support from the client. The module itself is included in the Windows 7 Remote Server Administration Tools (RSAT) package. After downloading and installing the package, you can enable it through the Turn Windows Features On or Off dialog in the Control Panel.

If working with the Active Directory module is an option at all, import it and use its commands. The Get-Command and Get-Help commands should be the two key steps you need to get started. In addition to the help built into the commands, @TODO_LH-Ref-ActiveDirectoryBook?

If the Active Directory module is not an option, PowerShell provides fluid integration with Active Directory through its [adsi] and [adsisearcher] built-in type shortcuts. This chapter covers their use for most common Active Directory tasks.

1 comment

  1. Jerome L Cruz Posted 17 days and 19 hours ago

    "...and [adsisearcher] type accelerators."

Add a comment

Test Active Directory Scripts on a Local Installation

Problem

You want to test your Active Directory scripts against a local installation.

Solution

To test your scripts against a local system, install Active Directory Lightweight Directory Services (AD LDS) and its sample configuration.

Discussion

For most purposes, Active Directory Lightweight Services works as a lightweight version of Active Directory. While it doesn't support any of Active Directory's infrastructure features, its programming model is close enough that you can easily use it to experiment with Active Directory scripting. Until recently, Active Directory Lightweight Directory Services was known as Active Directory Application Mode (ADAM.) AD LDS is not supported on Windows XP, the Microsoft Download Center continues to provide a download of ADAM that supports Windows XP. To test your scripts against a local installation, you'll need to install either AD LDS or ADAM, and then create a test instance.

Verify prerequisites

If you want to test AD LDS on a recent server operating system, simply enable it through the Optional Component Manager.

If you want to install it on a client operating system, you have two options. If you have Windows 7, download AD LDS. If you have Windows XP (or want to install in Windows XP mode), download ADAM.

2 comments

  1. Jerome L Cruz Posted 17 days and 19 hours ago

    Actually, ADAM has been renamed "AD LDS" in Windows Server 2008 and, as of 2-16-2010, it 'can' be downloaded and installed on Windows 7 devices. The tools to manage it are part of the RSAT tools, so once installed, the AD LDS tools can be 'feature activated'. Here's a link to the MS site to download it: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=a45059af-47a8-4c96-afe3-93dab7b5b658 ... Also, here's a link which more fully describes this: http://msdn.microsoft.com/en-us/library/aa705886(VS.85).aspx As I have not used it yet, I do not know whether it follows the same coding structures (hopefully so).

  2. Lee Holmes Posted 15 days ago

    Awesome, thanks.

Add a comment

Install ADAM

To install AD LDS or ADAM, the first step is to download it. Microsoft provides both free of charge from the Download Center. You can obtain it by searching for "Active Directory Application Mode" or "AD LDS" at http://download.microsoft.com.

Once you've downloaded it, run the setup program. Figure 26.1, “ADAM's post-installation screen” shows the ADAM setup wizard on Windows XP.

Figure 26.1. ADAM's post-installation screen

ADAM's post-installation screen

No comments yet

Add a comment

Create a test instance

From the ADAM menu in the Windows Start menu, select Create an ADAM instance. In the Setup Options page that appears next, select A unique instance. In the Instance Name page, type Test as an instance name. Accept the default ports, and then select Yes. Create an application directory partition on the next page. As the partition name, type DC=Fabrikam,DC=COM, as shown in Figure 26.2, “Creating a partition of a test ADAM instance”.

In the next pages, accept the default file locations, service accounts, and administrators.

When the setup wizard gives you the option to import LDIF files, import all available files except for MS-AZMan.LDF. Click Next on this page and the confirmation page to complete the instance setup.

Figure 26.2. Creating a partition of a test ADAM instance

Creating a partition of a test ADAM instance

Open a PowerShell window, and test your new instance:

PS > [adsi] "LDAP://localhost:389/dc=Fabrikam,dc=COM"

distinguishedName
-----------------
{DC=Fabrikam,DC=COM}

The [adsi] tag is a type shortcut, like several other type shortcuts in PowerShell. The [adsi] type shortcut provides a quick way to create and work with directory entries through Active Directory Service Interfaces.

Although scripts that act against an ADAM test environment are almost identical to those that operate directly against Active Directory, there are a few minor differences. ADAM scripts specify the host and port in their binding string (that is, localhost:389/), whereas Active Directory scripts do not.

For more information about type shortcuts in PowerShell, see the section called “Working with the .NET Framework”.

Create an Organizational Unit

Problem

You want to create an organizational unit (OU) in Active Directory.

Solution

To create an organizational unit in a container, use the [adsi] type shortcut to bind to a part of the Active Directory, and then call the Create() method.

$domain = [adsi] "LDAP://localhost:389/dc=Fabrikam,dc=COM"
$salesOrg = $domain.Create("OrganizationalUnit", "OU=Sales")
$salesOrg.Put("Description", "Sales Headquarters, SF")
$salesOrg.Put("wwwHomePage", "http://fabrikam.com/sales")
$salesOrg.SetInfo()

Discussion

The solution shows an example of creating a Sales organizational unit (OU) at the root of the organization. You can use the same syntax to create OUs under other OUs as well. Example 26.1, “Creating North, East and West sales divisions” demonstrates how to create more sales divisions.

Example 26.1. Creating North, East and West sales divisions

$sales = [adsi] "LDAP://localhost:389/ou=Sales,dc=Fabrikam,dc=COM"

$east = $sales.Create("OrganizationalUnit", "OU=East")
$east.Put("wwwHomePage", "http://fabrikam.com/sales/east")
$east.SetInfo()

$west = $sales.Create("OrganizationalUnit", "OU=West")
$west.Put("wwwHomePage", "http://fabrikam.com/sales/west")
$west.SetInfo()

$north = $sales.Create("OrganizationalUnit", "OU=North")
$north.Put("wwwHomePage", "http://fabrikam.com/sales/north")
$north.SetInfo()

When you initially create an item, notice that you need to use the Put() method to set properties on the new item. Once you've created the item, you can instead use simple property access to change those properties. For more information about changing properties of an organizational unit, see the section called “Modify Properties of an Organizational Unit”.

To see that these OUs have been created, see the section called “Get the Children of an Active Directory Container”.

Get the Properties of an Organizational Unit

Problem

You want to get and list the properties of a specific OU.

Solution

To list the properties of an OU, use the [adsi] type shortcut to bind to the OU in Active Directory, and then pass the OU to the Format-List cmdlet:

$organizationalUnit =
  [adsi] "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$organizationalUnit | Format-List *

Discussion

The solution retrieves the Sales West OU. By default, the Format-List cmdlet shows only the distinguished name of the group, so we type Format-List * to display all properties.

If you know which property you want the value of, you can specify it by name:

PS > $organizationalUnit.wWWHomePage
http://fabrikam.com/sales/west

If you are having trouble getting a property that you know exists, you can also retrieve the property using the Get() method on the container. While the name property can be accessed using the usual property syntax, the following example demonstrates the alternate approach:

1 comment

  1. Aleksandar Nikolic Posted 14 days ago

    approach:: --> approach:

Add a comment

PS > $organizationalUnit.Get("name")
West

Modify Properties of an Organizational Unit

Problem

You want to modify properties of a specific OU.

Solution

To modify the properties of an OU, use the [adsi] type shortcut to bind to the OU in Active Directory. If the property has already been set, you can change the value of a property as you would with any other PowerShell object. If you are setting a property for the first time, use the Put() method. Finally, call the SetInfo() method to apply the changes.

$organizationalUnit =
  [adsi] "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$organizationalUnit.Put("Description", "Sales West Organization")
$organizationalUnit.wwwHomePage = "http://fabrikam.com/sales/west/fy2012"
$organizationalUnit.SetInfo()

Discussion

The solution retrieves the Sales West OU. It then sets the description to Sales West Organization, updates the home page, and then applies those changes to Active Directory.

Delete an Organizational Unit

Problem

You want to delete a specific OU.

Solution

To delete an OU, use the [adsi] type shortcut to bind to the OU in Active Directory. Finally, call its DeleteTree() method to apply the changes.

$organizationalUnit =
  [adsi] "LDAP://localhost:389/ou=North,ou=Sales,dc=Fabrikam,dc=COM"
$organizationalUnit.DeleteTree()

Discussion

The solution retrieves the Sales North OU. It then calls the DeleteTree() method to permanently delete the organizational unit and all of its children.

Get the Children of an Active Directory Container

Problem

You want to list all the children of an Active Directory container.

Solution

To list the items in a container, use the [adsi] type shortcut to bind to the OU in Active Directory, and then access the Children property of that container:

$sales =
  [adsi] "LDAP://localhost:389/ou=Sales,dc=Fabrikam,dc=COM"
$sales.Children

Discussion

The solution lists all the children of the Sales OU. This is the level of information you typically get from selecting a node in the ADSIEdit MMC snapin. If you want to filter this information to include only users, other organizational units, or more complex queries, see the section called “Search for a User Account”.

In PowerShell version one, this solution used to require that you access $sales.PsBase.Children. This issue was resolved in PowerShell version two.

Create a User Account

Problem

You want to create a user account in a specific OU.

Solution

To create a user in a container, use the [adsi] type shortcut to bind to the OU in Active Directory, and then call the Create() method:

$salesWest =
  [adsi] "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$user = $salesWest.Create("User", "CN=MyerKen")
$user.Put("userPrincipalName", "Ken.Myer@fabrikam.com")
$user.Put("displayName", "Ken Myer")
$user.SetInfo()

Discussion

The solution creates a user under the Sales West organizational unit. It sets the userPrincipalName (a unique identifier for the user), as well as the user's display name.

Note

If this step generates an error saying, "The specified directory service attribute or value does not exist," verify that you properly imported the LDIF files at the beginning of the ADAM installation steps. Importing those LDIF files creates the Active Directory schema required for many of these steps.

When you run this script against a real Active Directory deployment (as opposed to an ADAM instance), be sure to update the sAMAccountName property, or you'll get an autogenerated default.

To see that these users have been created, see the section called “Get the Children of an Active Directory Container”. If you need to create users in bulk, see the section called “Program: Import Users in Bulk to Active Directory”.

Program: Import Users in Bulk to Active Directory

When importing several users into Active Directory, it quickly becomes tiresome to do it by hand (or even to script the addition of each user one-by-one). To solve this problem, we can put all our data into a CSV, and then do a bulk import from the information in the CSV.

Example 26.2, “Import-ADUser.ps1” supports this in a flexible way. You provide a container to hold the user accounts and a CSV that holds the account information. For each row in the CSV, the script creates a user from the data in that row. The only mandatory column is a CN column to define the common name of the user. Any other columns, if present, represent other Active Directory attributes you want to define for that user.

Example 26.2. Import-ADUser.ps1


param(
  $container = $(throw "Please specify a container (such as " +
    "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM)"),
  $csvPath = $(throw "Please specify the path to the users CSV")
  )

$userContainer = [adsi] $container

if(-not $userContainer.Name)
{
    Write-Error "Could not connect to $container"
    return
}

$users = @(Import-Csv $csvPath)
if($users.Count -eq 0)
{
    return
}

foreach($user in $users)
{
    $username = $user.CN
    $newUser = $userContainer.Create("User", "CN=$username")

    foreach($property in $user.PsObject.Properties)
    {
        if($property.Name -eq "CN")
        {
            continue
        }

        if(-not $property.Value)
        {
            continue
        }

        $newUser.Put($property.Name, $property.Value)
    }
    
    $newUser.SetInfo()
}
      

For more information about running scripts, see the section called “Run Programs, Scripts, and Existing Tools”.

Search for a User Account

Problem

You want to search for a specific user account, but don't know the user's distinguished name (DN).

Solution

To search for a user in Active Directory, use the [adsi] type shortcut to bind to a container that holds the user account, and then use the [adsisearcher] type shortcut to search for the user:

$domain = [adsi] "LDAP://localhost:389/dc=Fabrikam,dc=COM"
$searcher = [adsisearcher] $domain
$searcher.Filter = '(&(objectClass=User)(displayName=Ken Myer))'
$userResult = $searcher.FindOne()
$user = $userResult.GetDirectoryEntry()
$user

Discussion

When you don't know the full distinguished name (DN) of a user account, the [adsisearcher] type shortcut lets you search for it.

You provide an LDAP filter (in this case, searching for users with the display name of Ken Myer), and then call the FindOne() method. The FindOne() method returns the first search result that matches the filter, so we retrieve its actual Active Directory entry. Although the solution searches on the user's display name, you can search on any field in Active Directory—the userPrincipalName and sAMAccountName are two other good choices.

When you do this search, always try to restrict it to the lowest level of the domain possible. If we know that Ken Myer is in the Sales OU, it would be better to bind to that OU instead:

$domain = [adsi] "LDAP://localhost:389/ou=Sales,dc=Fabrikam,dc=COM"

For more information about the LDAP search filter syntax, search http://msdn.microsoft.com for "Search Filter Syntax."

Get and List the Properties of a User Account

Problem

You want to get and list the properties of a specific user account.

Solution

To list the properties of a user account, use the [adsi] type shortcut to bind to the user in Active Directory, and then pass the user to the Format-List cmdlet:

$user =
  [adsi] "LDAP://localhost:389/cn=MyerKen,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$user | Format-List *

Discussion

The solution retrieves the MyerKen user from the Sales West OU. By default, the Format-List cmdlet shows only the distinguished name of the user, so we type Format-List * to display all properties.

If you know the property for which you want the value, specify it by name:

PS > $user.DirectReports
CN=SmithRobin,OU=West,OU=Sales,DC=Fabrikam,DC=COM
CN=DoeJane,OU=West,OU=Sales,DC=Fabrikam,DC=COM

If you are having trouble getting a property that you know exists, you can also retrieve the property using the Get() method on the container. While the userPrincipalName property can be accessed using the usual property syntax, the following example demonstrates the alternate approach:

PS > $user.Get("userPrincipalName")
Ken.Myer@fabrikam.com

Modify Properties of a User Account

Problem

You want to modify properties of a specific user account.

Solution

To modify a user account, use the [adsi] type shortcut to bind to the user in Active Directory. If the property has already been set, you can change the value of a property as you would with any other PowerShell object. If you are setting a property for the first time, use the Put() method. Finally, call the SetInfo() method to apply the changes.

$user =
  [adsi] "LDAP://localhost:389/cn=MyerKen,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$user.Put("Title", "Sr. Exec. Overlord")
$user.SetInfo()

Discussion

The solution retrieves the MyerKen user from the SalesWest OU. It then sets the user's title to Sr. Exec. Overlord and applies those changes to Active Directory.

Change a User Password

Problem

You want to change a user's password.

Solution

To change a user's password, use the [adsi] type shortcut to bind to the user in Active Directory, and then call the SetPassword() method:

$user =
  [adsi] "LDAP://localhost:389/cn=MyerKen,ou=West,ou=Sales,dc=Fabrikam,dc=COM"
$user.SetPassword("newpassword")

Discussion

Changing a user password in Active Directory is a relatively straight-forward operation, and requires simply calling the SetPassword() method.

Note

Unfortunately, configuring your local experimental ADAM instance to support password changes is complicated and beyond the scope of this book.

One thing to notice is that the SetPassword() method takes a plain-text password as its input. Active Directory protects this password as it sends it across the network, but storing passwords securely until needed is a security best practice. the section called “Securely Handle Sensitive Information” discusses how to handle sensitive strings, and also shows you how to convert it back to plain text when needed.

Create a Security or Distribution Group

Problem

You want to create a security or distribution group.

Solution

To create a security or distribution group, use the [adsi] type shortcut to bind to a container in Active Directory, and then call the Create() method:

$salesWest =
  [adsi] "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM"
$management = $salesWest.Create("Group", "CN=Management")
$management.SetInfo()

Discussion

The solution creates a group named Management in the Sales West OU.

Note

When you run this script against a real Active Directory deployment (as opposed to an ADAM instance), be sure to update the sAMAccountName property, or you'll get an autogenerated default.

When you create a group in Active Directory, it is customary to also set the type of group by defining the groupType attribute on that group. To specify a group type, use the –bor operator to combine group flags and use the resulting value as the groupType property. Example 26.3, “Creating an Active Directory security group with a custom groupType” defines the group as a global, security-enabled group.

Example 26.3. Creating an Active Directory security group with a custom groupType

$ADS_GROUP_TYPE_GLOBAL_GROUP = 0x00000002
$ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = 0x00000004
$ADS_GROUP_TYPE_LOCAL_GROUP = 0x00000004
$ADS_GROUP_TYPE_UNIVERSAL_GROUP = 0x00000008
$ADS_GROUP_TYPE_SECURITY_ENABLED = 0x80000000

$salesWest =
  [adsi] "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$groupType = $ADS_GROUP_TYPE_SECURITY_ENABLED -bor
    $ADS_GROUP_TYPE_GLOBAL_GROUP

$management = $salesWest.Create("Group", "CN=Management")
$management.Put("groupType", $groupType)
$management.SetInfo()

If you need to create groups in bulk from the data in a CSV, the Import-ADUser script given in the section called “Program: Import Users in Bulk to Active Directory” provides an excellent starting point. To make the script create groups instead of users, change this line:

$newUser = $userContainer.Create("User", "CN=$username")

to this:

$newUser = $userContainer.Create("Group", "CN=$username")

If you change the script to create groups in bulk, it is helpful to also change the variable names ($user, $users, $username, and $newUser) to correspond to group-related names: $group, $groups, $groupname, and $newgroup.

Search for a Security or Distribution Group

Problem

You want to search for a specific group, but don't know its distinguished name (DN).

Solution

To search for a security or distribution group, use the [adsi] type shortcut to bind to a container that holds the group, and then use the [adsisearcher] type shortcut to search for the group:

$domain = [adsi] "LDAP://localhost:389/dc=Fabrikam,dc=COM"
$searcher = [adsisearcher] $domain
$searcher.Filter = '(&(objectClass=Group)(name=Management))'
$grosrResult = $searcher.FindOne()
$group = $groupResult.GetDirectoryEntry()
$group

Discussion

When you don't know the full distinguished name (DN) of a group, the [adsisearcher] type shortcut lets you search for it.

You provide an LDAP filter (in this case, searching for groups with the name of Management), and then call the FindOne() method. The FindOne() method returns the first search result that matches the filter, so we retrieve its actual Active Directory entry. Although the solution searches on the group's name, you can search on any field in Active Directory—the mailNickname and sAMAccountName are two other good choices.

When you do this search, always try to restrict it to the lowest level of the domain possible. If we know that the Management group is in the Sales OU, it would be better to bind to that OU instead:

$domain = [adsi] "LDAP://localhost:389/ou=Sales,dc=Fabrikam,dc=COM"

For more information about the LDAP search filter syntax, search http://msdn.microsoft.com for "Search Filter Syntax."

Get the Properties of a Group

Problem

You want to get and list the properties of a specific security or distribution group.

Solution

To list the properties of a group, use the [adsi] type shortcut to bind to the group in Active Directory, and then pass the group to the Format-List cmdlet:

$group =
  [adsi] "LDAP://localhost:389/cn=Management,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$group | Format-List *

Discussion

The solution retrieves the Management group from the Sales West OU. By default, the Format-List cmdlet shows only the DN of the group, so we type Format-List * to display all properties.

If you know the property for which you want the value, specify it by name:

PS > $group.Member
CN=SmithRobin,OU=West,OU=Sales,DC=Fabrikam,DC=COM
CN=MyerKen,OU=West,OU=Sales,DC=Fabrikam,DC=COM

If you are having trouble getting a property that you know exists, you can also retrieve the property using the Get() method on the container. While the name property can be accessed using the usual property syntax, the following example demonstrates the alternate approach:

PS > $group.Get("name")
Management

Find the Owner of a Group

Problem

You want to get the owner of a security or distribution group.

Solution

To determine the owner of a group, use the [adsi] type shortcut to bind to the group in Active Directory, and then retrieve the ManagedBy property:

$group =
  [adsi] "LDAP://localhost:389/cn=Management,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$group.ManagedBy

Discussion

The solution retrieves the owner of the Management group from the Sales West OU. To do this, it accesses the ManagedBy property of that group. This property exists only when populated by the administrator of the group, but it is a best practice to do so.

Modify Properties of a Security or Distribution Group

Problem

You want to modify properties of a specific security or distribution group.

Solution

To modify a security or distribution group, use the [adsi] type shortcut to bind to the group in Active Directory. If the property has already been set, you can change the value of a property as you would with any other PowerShell object. If you are setting a property for the first time, use the Put() method. Finally, call the SetInfo() method to apply the changes.

$group =
  [adsi] "LDAP://localhost:389/cn=Management,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

PS > $group.Put("Description", "Managers in the Sales West Organization")
PS > $group.SetInfo()

Discussion

The solution retrieves the Management group from the Sales West OU. It then sets the description to Managers in the Sales West Organization, and then applies those changes to Active Directory.

Add a User to a Security or Distribution Group

Problem

You want to add a user to a security or distribution group.

Solution

To add a user to a security or distribution group, use the [adsi] type shortcut to bind to the group in Active Directory, and then call the Add() method:

$management =
  [adsi] "LDAP://localhost:389/cn=Management,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$user = "LDAP://localhost:389/cn=MyerKen,ou=West,ou=Sales,dc=Fabrikam,dc=COM"
$management.Add($user)

Discussion

The solution adds the MyerKen user to a group named Management in the SalesWest OU. To see whether you have added the user successfully, see the section called “List a User's Group Membership”.

Remove a User from a Security or Distribution Group

Problem

You want to remove a user from a security or distribution group.

Solution

To remove a user from a security or distribution group, use the [adsi] type shortcut to bind to the group in Active Directory, and then call the Remove() method:

$management =
  [adsi] "LDAP://localhost:389/cn=Management,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$user = "LDAP://localhost:389/cn=MyerKen,ou=West,ou=Sales,dc=Fabrikam,dc=COM"
$management.Remove($user)

Discussion

The solution removes the MyerKen user from a group named Management in the Sales West OU. To see whether you have removed the user successfully, see the section called “List a User's Group Membership”.

List a User's Group Membership

Problem

You want to list the groups to which a user belongs.

Solution

To list a user's group membership, use the [adsi] type shortcut to bind to the user in Active Directory, and then access the MemberOf property:

$user =
  [adsi] "LDAP://localhost:389/cn=MyerKen,ou=West,ou=Sales,dc=Fabrikam,dc=COM"
$user.MemberOf

Discussion

The solution lists all groups in which the MyerKen user is a member. Since Active Directory stores this information as a user property, this is simply a specific case of retrieving information about the user. For more information about retrieving information about a user, see the section called “Get and List the Properties of a User Account”.

List the Members of a Group

Problem

You want to list all the members in a group.

Solution

To list the members of a group, use the [adsi] type shortcut to bind to the group in Active Directory, and then access the Member property:

$group =
  [adsi] "LDAP://localhost:389/cn=Management,ou=West,ou=Sales,dc=Fabrikam,dc=COM"
$group.Member

Discussion

The solution lists all members of the Management group in the Sales West OU. Since Active Directory stores this information as a property of the group, this is simply a specific case of retrieving information about the group. For more information about retrieving information about a group, see the section called “Get the Properties of a Group”.

List the Users in an Organizational Unit

Problem

You want to list all the users in an OU.

Solution

To list the users in an OU, use the [adsi] type shortcut to bind to the OU in Active Directory. Use the [adsisearcher] type shortctut to create a searcher for that OU, and then set its Filter property to (objectClass=User). Finally, call the searcher's FindAll() method to perform the search.

$sales =
  [adsi] "LDAP://localhost:389/ou=Sales,dc=Fabrikam,dc=COM"

$searcher = [adsisearcher] $sales
$searcher.Filter = '(objectClass=User)'
$searcher.FindAll()

Discussion

The solution lists all users in the Sales OU. It does this through the [adsisearcher] type shortcut, which lets you search and query Active Directory. The Filter property specifies an LDAP filter string.

Note

By default, an [adsisearcher] searches the given container and all containers below it. Set the SearchScope property to change this behavior. A value of Base searches only the current container, while a value of OneLevel searches only the immediate children.

For more information about working with classes from the .NET Framework, see the section called “Work with .NET Objects”.

Search for a Computer Account

Problem

You want to search for a specific computer account, but don't know its distinguished name (DN).

Solution

To search for a computer account, use the [adsi] type shortcut to bind to a container that holds the account, and then use the [adsisearcher] type shortcut to search for the account:

$domain = [adsi] "LDAP://localhost:389/dc=Fabrikam,dc=COM"
$searcher = [adsisearcher] $domain
$searcher.Filter = '(&(objectClass=Computer)(name=kenmyer_laptop))'
$computerResult = $searcher.FindOne()
$computer = $computerResult.GetDirectoryEntry()

Discussion

When you don't know the full distinguished name (DN) of a computer account, the [adsisearcher] type shortcut lets you search for it.

You provide an LDAP filter (in this case, searching for computers with the name of kenmyer_laptop), and then call the FindOne() method. The FindOne() method returns the first search result that matches the filter, so we retrieve its actual Active Directory entry. Although the solution searches on the computer's name, you can search on any field in Active Directory-the sAMAccountName and operating system characteristics (operatingSystem, operatingSystemVersion, operatingSystemServicePack) are other good choices.

When you do this search, always try to restrict it to the lowest level of the domain possible. If you know that the computer is in the Sales OU, it would be better to bind to that OU instead:

$domain = [adsi] "LDAP://localhost:389/ou=Sales,dc=Fabrikam,dc=COM"

For more information about the LDAP search filter syntax, search http://msdn.microsoft.com for "Search Filter Syntax."

Get and List the Properties of a Computer Account

Problem

You want to get and list the properties of a specific computer account.

Solution

To list the properties of a computer account, use the [adsi] type shortcut to bind to the computer in Active Directory, and then pass the computer to the Format-List cmdlet:

$computer =
  [adsi] "LDAP://localhost:389/cn=kenmyer_laptop,ou=West,ou=Sales,dc=Fabrikam,dc=COM"

$computer | Format-List *

Discussion

The solution retrieves the kenmyer_laptop computer from the Sales West OU. By default, the Format-List cmdlet shows only the distinguished name of the computer, so we type Format-List * to display all properties.

If you know the property for which you want the value, specify it by name:

PS > $computer.OperatingSystem
Windows Server 2003

If you are having trouble getting a property that you know exists, you can also retrieve the property using the Get() method on the container. While the operatingSystem property can be accessed using the usual property syntax, the following example demonstrates the alternate approach:

PS > $user.Get("operatingSystem")
Windows Server 2003
You must sign in or register before commenting
*
*
*
*
*

Atom Icon Comments on this page or Comments on the whole book.