Chapter 26. Active Directory

Introduction

By far, the one thing that makes system administration on the Windows platform 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.

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

While PowerShell version two was under development, the Active Directory team created an immensely feature-filled PowerShell module to manage Active Directory domains. The Active Directory module includes a PowerShell provider (Set-Location AD:) and almost 100 task-specific PowerShell cmdlets.

Working with the Active Directory module has two requirements:

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.

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, MSDN provides a great task-based introduction to the Active Directory Module at http://go.microsoft.com/fwlink/?linkid=168142.

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.

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. Although 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, and so 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 or Windows Vista, download AD LDS. If you have Windows XP (or want to install in Windows XP mode), download ADAM.

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 either 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 shows the ADAM setup wizard on Windows XP.

ADAM’s post-installation screen

Figure 26-1. ADAM’s post-installation screen

Create a test instance

From the ADAM menu in the Windows Start menu, select “Create an ADAM instance.” On the Setup Options page that appears next, select “A unique instance.” On the Instance Name page, type Test as an instance name. On the Ports page, accept the default ports, and then on the Application Directory Partition page, select “Yes, create an application directory partition.” As the partition name, type DC=Fabrikam,DC=COM, as shown in Figure 26-2.

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.

Creating a partition of a test ADAM instance

Figure 26-2. 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.

Note

When you first try this shortcut, you may receive this unhelpful error message:

format-default : The following exception occurred while retrieving 
member "PSComputerName": "Unknown error (0x80005000)"

If you receive this error, ensure that you’ve capitalized the LDAP in LDAP://localhost:389/.

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 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 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 Modify Properties of an Organizational Unit.

To check that these OUs have been created, see Get the Children of an Active Directory Container.

Using the Active Directory module, the cmdlet to create an organizational unit is New-ADOrganizationalUnit. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 alternative approach:

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

Using the Active Directory module, the cmdlet to get the properties of an organizational unit is Get-ADOrganizationalUnit. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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.

Using the Active Directory module, the cmdlet to modify the properties of an organizational unit is Set-ADOrganizationalUnit. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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.

Using the Active Directory module, the cmdlet to remove an organizational unit is Remove-ADOrganizationalUnit. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 snap-in. If you want to filter this information to include only users, other organizational units, or more complex queries, see 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.

Using the Active Directory module, the Active Directory provider lets you get the children of an organizational unit. For example:

PS > Set-Location 'AD:ou=Sales,dc=Fabrikam,dc=COM'
PS > dir

For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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", "[email protected]")
$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 check that these users have been created, see Get the Children of an Active Directory Container. If you need to create users in bulk, see Program: Import Users in Bulk to Active Directory.

Using the Active Directory module, the cmdlet to create a user account is New-ADUser. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 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

#############################################################################
##
## Import-AdUser
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
#############################################################################

<#

.SYNOPSIS

Create users in Active Directory from the content of a CSV.

.DESCRIPTION

In the user CSV, one column must be named "CN" for the user name.
All other columns represent properties in Active Directory for that user.

For example:
CN,userPrincipalName,displayName,manager
MyerKen,[email protected],Ken Myer,
DoeJane,[email protected],Jane Doe,"CN=MyerKen,OU=West,OU=Sales,DC=..."
SmithRobin,[email protected],Robin Smith,"CN=MyerKen,OU=West,OU=..."

.EXAMPLE

PS >$container = "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM"
PS >Import-ADUser.ps1 $container .users.csv

#>

param(
    ## The container in which to import users
    ## For example:
    ## "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM)")
    [Parameter(Mandatory = $true)]
    $Container,

    ## The path to the CSV that contains the user records
    [Parameter(Mandatory = $true)]
    $Path
)

Set-StrictMode -Off

## Bind to the container
$userContainer = [adsi] $container

## Ensure that the container was valid
if(-not $userContainer.Name)
{
    Write-Error "Could not connect to $container"
    return
}

## Load the CSV
$users = @(Import-Csv $Path)
if($users.Count -eq 0)
{
    return
}

## Go through each user from the CSV
foreach($user in $users)
{
    ## Pull out the name, and create that user
    $username = $user.CN
    $newUser = $userContainer.Create("User", "CN=$username")

    ## Go through each of the properties from the CSV, and set its value
    ## on the user
    foreach($property in $user.PsObject.Properties)
    {
        ## Skip the property if it was the CN property that sets the
        ## user name
        if($property.Name -eq "CN")
        {
            continue
        }

        ## Ensure they specified a value for the property
        if(-not $property.Value)
        {
            continue
        }

        ## Set the value of the property
        $newUser.Put($property.Name, $property.Value)
    }

    ## Finalize the information in Active Directory
    $newUser.SetInfo()
}

For more information about running scripts, see Run Programs, Scripts, and Existing Tools.

Search for a User Account

Problem

You want to search for a specific user account, but you 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. If you expect your query to return multiple results, use the FindAll() method instead. 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”.

Using the Active Directory module, the cmdlet to search for a user account is Get-ADUser. While you can use a LDAP filter to search for users, the Get-ADUser cmdlet also lets you supply PowerShell expressions:

Get-ADUser -Filter { Name -like "*Ken*" }

For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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")
[email protected]

Using the Active Directory module, the cmdlet to retrieve a user account is Get-ADUser. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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.

Using the Active Directory module, the cmdlet to modify a user account is Set-ADUser. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 straightforward operation, requiring 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. Securely Handle Sensitive Information discusses how to handle sensitive strings and also shows you how to convert one back to plain text when needed.

Using the Active Directory module, the cmdlet to change a user password is Set-ADAccountPassword. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 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 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.

Using the Active Directory module, the cmdlet to create a group is New-ADGroup. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

Search for a Security or Distribution Group

Problem

You want to search for a specific group, but you 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))'
$groupResult = $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. If you expect your query to return multiple results, use the FindAll() method instead. 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”.

Using the Active Directory module, the cmdlet to search for a security or distribution group is Get-ADGroup. While you can use a LDAP filter to search for a group, the Get-ADGroup cmdlet also lets you supply PowerShell expressions:

Get-ADGroup -Filter { Name -like "*Management*" }

For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 alternative approach:

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

Using the Active Directory module, the cmdlet to get the properties of a group is Get-ADGroup. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 is fairly reliable: Active Directory administrators consider it a best practice to create and populate this property.

Using the Active Directory module, the cmdlet to find the owner of a group is Get-ADGroup. This cmdlet does not retrieve the ManagedBy property by default, so you also need to specify ManagedBy as the value of the -Property parameter. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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()
PS > $group.Description

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.

Using the Active Directory module, the cmdlet to modify the properties of a security or distribution group is Set-ADGroup. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 check whether you have added the user successfully, see List a User’s Group Membership.

Using the Active Directory module, the cmdlet to add a user to a security or distribution group is Add-ADGroupMember. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 check whether you have removed the user successfully, see List a User’s Group Membership.

Using the Active Directory module, the cmdlet to remove a user from a security or distribution group is Remove-ADGroupMember. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 Get and List the Properties of a User Account.

Using the Active Directory module, the cmdlet to retrieve a user’s group membership is Get-ADUser. This cmdlet does not retrieve the MemberOf property by default, so you also need to specify MemberOf as the value of the -Property parameter. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 Get the Properties of a Group.

Using the Active Directory module, the cmdlet to list the members of a security or distribution group is Get-ADGroupMember. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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 shortcut 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, whereas a value of OneLevel searches only the immediate children.

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

Using the Active Directory module, the cmdlet to list the users in an organizational unit is Get-ADUser. To restrict the results to a specific organizational unit, specify that organizational unit as the -SearchBase parameter. Alternatively, navigate to that path in the Active Directory provider, and then call the Get-ADUser cmdlet. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

Search for a Computer Account

Problem

You want to search for a specific computer account, but you 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.

Note

This recipe requires a full Active Directory instance, as neither ADAM nor AD LDS supports computer objects.

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. If you expect your query to return multiple results, use the FindAll() method instead. 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”.

Using the Active Directory module, the cmdlet to search for a computer account is Get-ADComputer. While you can use a LDAP filter to search for computer, the Get-ADComputer cmdlet also lets you supply PowerShell expressions:

Get-ADComputer -Filter { Name -like "*kenmyer*" }

For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

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.

Note

This recipe requires a full Active Directory instance, as neither ADAM nor AD LDS supports computer objects.

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 alternative approach:

PS > $computer.Get("operatingSystem")
Windows Server 2003

Using the Active Directory module, the cmdlet to list the properties of a computer account is Get-ADComputer. For more information on how to accomplish these tasks through the Active Directory module, see http://go.microsoft.com/fwlink/?linkid=168142.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.76.164