Administration of accounts in the Active Directory domain. Active Directory domain - what it is in simple words, description and reviews

17.03.2014 Darren Mar-Elia

When Windows PowerShell first came out, many people asked whether it was possible to manage Active Directory(AD) using PowerShell. At the time, Microsoft's response was not what most administrators would have liked to hear. PowerShell had a built-in Active Directory Service Interfaces (ADSI) "type accelerator" for accessing AD objects, but the user largely had to figure out on their own how to use PowerShell to perform AD administration tasks. Significant changes occurred with the release Windows Server 2008 R2, which introduced the PowerShell module for Active Directory. The AD module includes a set of commands for managing AD, as well as an AD Provider that allows you to navigate AD like a symbolic drive. In this article I will show you how to install the AD module and describe its functioning in detail

When Windows PowerShell first came out, many people asked if it was possible to manage Active Directory (AD) using PowerShell. At the time, Microsoft's response was not what most administrators would have liked to hear. PowerShell had a built-in Active Directory Service Interfaces (ADSI) “type accelerator” for accessing AD objects, but the user largely had to figure out on their own how to use PowerShell to perform AD administration tasks. Over time, Quest Software has provided a free set of commands for AD administrative tasks, including creating, modifying, and deleting AD objects, and searching for objects in AD. This has been the state of PowerShell and AD management for a long time.

Significant changes occurred with the release of Windows Server 2008 R2, which introduced the PowerShell module for Active Directory. The AD module includes a set of commands for managing AD, as well as an AD Provider that allows you to navigate AD like a symbolic drive. In this article, I will show you how to install the AD module and describe its functioning in detail.

Installing Active Directory Module

Unlike previous tools that used LDAP to communicate with AD, the AD module uses Active Directory Web Services (ADWS) protocols to communicate with the AD domain controller (DC). These protocols are described in detail in the MSDN blog "Active Directory Web Services Overview", but suffice it to note that the PowerShell commands in the AD module and the Active Directory Administrative Center (ADAC) use ADWS to communicate with and retrieve information from AD.

When you install Windows Server 2012 or Server 2008 R2 domain controllers in an AD domain, the ADWS protocol is installed and running by default on each of them. If your domain consists entirely of Windows Server 2008 or Windows Server 2003 domain controllers, you must install ADWS separately. Microsoft provides the Active Directory Management Gateway Service package free of charge for this purpose. If you install the package on at least one AD Server 2008 or Server 2003 domain controller, you can use the AD module for PowerShell along with ADAC.

The AD module itself is installed by default on any DC running the Server 2012 or Server 2008 R2 operating system. On Windows computers 8 and Windows 7 (or any computer other than a DC running Server 2012 or Server 2008 R2), you must install the Remote Server Administration Tools from the Microsoft Download Center.

Regardless of whether Remote Server Administration Tools are installed on your computer in advance or separately, the next step is to open the Add/Remove Programs section in Control Panel and select Turn Windows features on or off from the menu on the left. . Scroll down the Windows Features dialog box to the Remote Server Administration Tools section. Locate the Active Directory Module for Windows PowerShell checkbox in the \Remote Server Administration Tools\Role Administration Tools\AD DS and AD LDS Tools folder, as Figure 1 shows. Select the checkbox and click OK to install the module.

You should now see a shortcut for Active Directory Module for Windows PowerShell in the Administrative Tools section of the Start menu. Click this shortcut to launch PowerShell with the AD module loaded. If you're already working in PowerShell and just want to load the module so it's available for use, you can enter the following command to gain access to the AD and AD Provider commands:

Import-Module ActiveDirectory

Now let's see how to navigate AD using AD Provider.

Using the Active Directory Provider

PowerShell implements the concept of PowerShell drives, which I will simply refer to as PS drives. To put it simply, a PS drive is a representation of a resource, such as a navigable file system consisting of folders and leaf items. Not every resource can be thought of this way, but many (including AD and the registry) fit well into this model. The AD module contains the provider for the PS AD disk. Accordingly, you can navigate and even change AD as if it were a file system.

How to navigate AD using AD Provider? This assumes that PowerShell is open and the AD module is loaded. In this case, the first step is to run the Set-Location command, which has several aliases, including sl and cd:

Set-Location AD:

This command changes the current working location of the PS AD drive. As a result, the PowerShell prompt will show AD:\ instead of C:\. Then, to see the items in the PS AD drive, you can use the Get-ChildItem command with the dir alias:

Get-ChildItem

Figure 2 shows an example of the result on my computer.

As we can see, the command returns a list of all available domain partitions. The most interesting one, in my opinion, is the domain section called cpandl, which contains user and computer names. To change this domain, just enter the command:

Set-Location "dc=cpandl,dc=com"

Note that the Set-Location command is used with the distinguished name (DN) of my AD domain. This is required for correct navigation. Once you've navigated to your domain directory (as indicated by the AD:\dc=cpandl,dc=com prompt in PowerShell), you can use the Get-ChildItem command to see the top-level AD structure (Figure 3).


Figure 3: Viewing the Top Level of the AD Hierarchy

If you want to look at the users in the SDM organizational unit (OU), then to navigate to that OU you just need to enter:

Set-Location "OU=SDM"

The PowerShell command line will look like AD:\ou=SDM,dc=cpandl,dc=com. On at this stage you can use the Get-ChildItem command to see all user objects in this OU. If I need to change the Description property on the user object representing my Darren Mar-Elia user account. There's a team for that! The Set-ItemProperty command allows you to change a property on an AD object. If you need to change the description of the user account on Chief Techie, you should run the command:

Set-ItemProperty -Path ".\CN=Darren Mar-Elia" ` -Name "Description" -Value "Chief Techie"

As we can see, the –Path parameter is used here to specify my user account in the current directory. I also use the -Name parameter to indicate that the Description property needs to be changed, and the –Value parameter to specify the Chief Techie's description.

Note that if you want to find all objects with a particular property value, you can use Get-ItemProperty. If you just want to get a reference to an AD object, use Get-Item.

As you can see, working with AD in this way is quite simple. The mechanism is hardly suitable for bulk changes, but it is convenient for working with AD as a file system. However, as I found out, most administrators use commands instead of the PS AD drive to manage AD. Let's see how some of these commands work.

Using Active Directory Commands

The AD module included with Windows 7 contains 76 commands for managing AD. They can be used for almost any purpose, including finding AD objects, creating and deleting AD objects, and manipulating AD configuration information (such as forest mode and granular password policies). Typically commands are grouped by verbs such as Add-, Remove-, Get- and Set-. Note that not every Get- command has a corresponding Set- command and vice versa, so sometimes you have to spend some effort to find the right command for the task. For example, you can set the AD forest functionality level using Set-ADForestMode, but to find out the current forest functionality level, you must use the Get-ADForest command and look at the ForestMode property on the returned object.

Let's look at a few common tasks that can be performed using AD commands. Specifically, we'll show you how to add user accounts, manage group membership, reset user account passwords, and search AD objects.

Adding user accounts

The New-ADUser command provides an easy way to add user accounts to AD. If you want to add a new user account named Bill Smith to the SDM organizational unit, then in the simplest case you can create a new user account using the command:

New-ADUser -Name "Bill Smith" -SamAccountName "bsmith" ` -GivenName "Bill" -Surname "Smith" ` -DisplayName "Bill Smith" -Path "OU=SDM,DC=cpandl,DC=com"

This command enters basic information about the user account. Specifically, the -SamAccountName parameter is used to provide the name of the SAM account required to create the user object. The –Path parameter is also used to tell the command where to place the object - in this case, the SDM OU in the cpandl.com domain. In addition, the user's first name (-GivenName parameter), last name (-Surname parameter), and display name (-DisplayName parameter) are specified.

Running this command will create a user account, but there are two problems. First, the account will be disabled. Second, the account will not have a password associated with it, which is required on most domains.

To avoid having to activate the account and assign a password separately, you can modify the New-ADUser command. New-ADUser will automatically enable the account if you specify the -Enabled $true parameter in the command. Activation requires a password, so you must also specify it in the command.

To provide a password, you can use the –AccountPassword parameter. However, you cannot enter the password in plain text at the command prompt. This option requires that the password be entered in a secure string (that is, it has a SecureString data type). There are two ways to convert a password to a secure string, and both use a variable.

The first method uses the ConvertTo-SecureString command, which converts plain text strings to secure strings. For example, if you want to convert the password P@ssw0rd12 to a protected string and assign it to the $pwd variable, you would run the command:

$pwd = ConvertTo-SecureString -string "P@ssw0rd12" ` -AsPlainText –force

This is not the most secure method of assigning a password, as someone could look over your shoulder when you enter the command. A more secure method is to have the New-ADUser command prompt for a password and hide characters entered. This can be done using the Read-Hostcmdlet command with the –AsSecureString parameter:

$pwd = Read-Host -AsSecureString

After running this command, you will see the familiar "*" symbol on your screen when entering your password. When you are finished, press the Enter key.

Once the password is stored in the $pwd variable, you can pass it to the New-ADUser command:

New-ADUser -Name"Bill Smith"-SamAccountName"bsmith"` -GivenName"Bill"-Surname"Smith"` -DisplayName"Bill Smith"` -Path"OU=SDM,DC=cpandl,DC=com"` - Enabled $true -AccountPassword $pwd

As we can see, the command contains the -Enabled and –AccountPassword parameters, which enable the account and securely assign a password to it.

Creating user accounts one at a time is a neat way, but sometimes you need to create multiple accounts at the same time. PowerShell is great for this purpose. For example, if you need to create three user accounts, you can prepare a comma separated value (CSV) file that contains account information and then use the Import-CSV command to transfer that information to New-ADUser.

Figure 4 shows a CSV file named userlist.csv.

Note that in this file, the column headings correspond to the parameter names provided in the previous New-ADUser command. This was done on purpose. When the CSV data is passed to New-ADUser, the command will pick up those parameter names from the PowerShell pipeline and won't have to be specified in the command itself. Here is the command used to create three user accounts:

Import-CSV -Path C:\data\userlist.csv | New-ADUser -Enabled $true -AccountPassword $pwd

As you can see, the output of the Import-CSV command goes to the New-ADUser command. The pipeline recognizes that the column headers in the CSV file are parameter names and the remaining rows contain values, so you only need to supply the -Enabled and –AccountPassword parameters. This is an excellent conveyor capability. It allows you to use PowerShell much more effectively for these types of automation tasks.

Group Membership Management

Adding user and computer accounts is a typical AD management task. Using the AD module, this is relatively easy to accomplish. Using the Add-ADGroupMember command, you can add one or more accounts to a group. For example, if you need to add three new users to the Marketing Users group. The easiest way is to use the command:

Add-ADGroupMember -Identity»Marketing Users«` -Members jadams,tthumb,mtwain

In this command, the -Identity parameter is used to provide the group name. The -Members parameter is also used to provide the user SAM account names. If there are multiple SAM account names, they should be listed in a comma-separated file.

You can combine the operations of creating three accounts and adding them to the Marketing Users group in one command to solve the problem in one action. However, the Add-ADGroupMember command does not support passing group member names into the pipeline. Therefore, you must use the Add-ADPrincipalGroupMembership command if you want to use the pipeline. This command can accept user, computer, or group objects as input from a pipeline and add those objects to the specified group.

You can combine the operation of creating users with the operation of adding new users to the Marketing Users group in one command as follows:

Import-CSV -Path C:\data\userlist.csv | New-ADUser -Enabled $true -AccountPassword $pass ` -PassThru | Add-ADPrincipalGroupMembership ` -MemberOf"Marketing Users"

Note that the –PassThru parameter has been added to the New-ADUser part of the command. This parameter tells New-ADUser to pass created user objects into the pipeline. If this parameter is not specified, the Add-ADPrincipalGroupMembership command will fail.

It's also notable that only the -MemberOf parameter is used to specify the group name in the Add-ADPrincipalGroupMembership section of the command. The pipeline takes care of the rest by adding each of the three users to the Marketing Users group.

So, using one PowerShell command, three new users were created, they were placed in the OU, they were given passwords, and they were added to the Marketing Users group. Now let's look at some other common AD maintenance tasks that can be automated using PowerShell and the AD module.

Resetting user account passwords

Sometimes users need to reset their account password. This task can be easily automated using the Set-ADAccountPassword command by changing or resetting the account password. To change the password, you need to know the old password and enter the new one. To reset your password, simply provide a new password. However, you must have Reset Password permission on the user object in AD to perform a password reset.

Like the -AccountPassword parameter of the New-ADUser command, the Set-ADAccountPassword command uses the SecureString data type for passwords, so you must use one of the methods to convert plain text passwords to secure strings. For example, if you want to reset the password for the Tom Thumb user account, after storing the new password as a protected string in the $pass variable, you can run the command:

Set-ADAccountPassword -Identity»tthumb«` -NewPassword $pass –Reset

In this command, I use the –Identity parameter to assign a SAM account name to the Tom Thumb user account. I also enter the -NewPassword parameter with the $pass variable to provide a new password. Finally, the –Reset parameter is specified to indicate that a reset is being performed rather than a password change.

Another optional task: toggle the Tom Thumb user account flag to force him to change his password the next time he logs in. This is a common technique when you need to reset a user's password. This task can be performed using the Set-ADUser command, setting the -ChangePasswordAtLogon parameter to $true:

Set-ADUser -Identity tthumb -ChangePasswordAtLogon $true

The question arises as to why a pipeline was not used to pass the output of the Set-ADAccountPassword command to the Set-ADUser command to perform both operations in one PowerShell command. I tried this approach, it doesn't work. There is probably some limitation in the Set-ADAccountPassword command that prevents the single command from running successfully. In any case, it is sufficient to simply toggle the flag using the Set-ADUser command as shown above.

Searching for Active Directory Objects

Another typical AD task is to find AD objects that meet certain criteria. For example, you can find all computers running a specific version of the Windows operating system in an AD domain. The Get-ADObject command is the most convenient for LDAP searching. For example, to find Server 2008 R2 computers in the cpandl.com domain, the command was used:

Get-ADObject -LDAPFilter ` "(&(operatingSystem=Windows Server 2008 R2 Enterprise)` (objectClass=computer))" -SearchBase"dc=cpandl,dc=com"` -SearchScope Subtree

This command uses three parameters to perform the task: -LDAPFilter, -SearchBase, and -SearchScope. The -LDAPFilter parameter takes a standard LDAP query as input. This example queries all computer objects that have the OperatingSystem attribute set to Windows Server 2008 R2 Enterprise. The -SearchBase parameter tells the command where to start searching in the AD hierarchy. In this case, the search is performed from the root directory of the AD domain, but it is not difficult to limit the search to a specific OU. The –SearchScope parameter tells the command whether to crawl all containers under the search base, finding the specified objects. In this case, the Subtree parameter is used to force the command to check all underlying containers.

When you run the command, objects that match the criteria are displayed. Or you can forward the results to another command to process the found objects.

Note that for large searches it is useful to use the –ResultPageSize parameter to control how the search results are paginated. Typically I set this parameter to 1000 and the Get-ADObject command returns 1000 objects at a time. Otherwise, you may not get the expected result because the number of objects returned exceeds the maximum allowed by the policy set for a single search request.

Another search command provided by Microsoft is Search-ADAccount. This command is especially useful for searching with various predefined conditions, such as disabled accounts, accounts with expired passwords, and locked out accounts. So, the following command finds all user accounts with expired passwords in the SDM OU:

Search-ADAccount -PasswordExpired -UsersOnly ` -SearchBase"OU=sdm,dc=cpandl,dc=com" -SearchScope OneLevel Search-ADAccount -PasswordExpired -UsersOnly ` -SearchBase"OU=sdm,dc=cpandl,dc=com" ` -SearchScope OneLevel

This command uses the –PasswordExpired parameter to specify that accounts with expired passwords are required. The -UsersOnly parameter specifies that only user objects should be searched (that is, computer objects should be excluded). As in the previous example, the -SearchBase and –SearchScope parameters are used to specify the search scope. But in this case, I'm using the OneLevel parameter to search only the closest OU (that is, excluding any child organizational units).

This is just the surface of the AD module, but I hope you get an idea of ​​its capabilities. As noted above, there are more than 70 commands in the module. Topics not covered in this article include deleting objects using the Remove- command, restoring deleted objects using the Restore-ADObject command, and removing UAC properties on user objects using the Set-ADAccountControl command. There are commands for almost any AD administrative task.



Lesson 7. Active Directory Administration.

The Active Directory administration process involves managing:

  • Active Directory domains;
  • domain directory structure;
  • domain objects (users, contacts, computers, groups, printers, etc.);
  • Active Directory sites and networks;
  • data replication.

All these tasks are solved using three management consoles that are installed during the installation of Active Directory on a domain controller:

  • Active Directory - Domains and Trust
  • Active Directory - Users and Computers
  • Active Directory - Sites and Services

These consoles can be installed on other computers in the domain as part of a package of administrative utilities.

Description of Active Directory objects.

All Active Directory management consoles use a single set of icons to display directory objects. Below are all the main Active Directory objects and their corresponding icons. This information will help you navigate Active Directory more easily.

Active Directory

Represents Active Directory as a whole. Almost never found in management tools, with the exception of search and object selection windows

Represents a Windows domain. Allows you to manage global domain settings

Container, folder

Represents a simple container object. Such objects can only be created by the operating system and are usually generated during the installation of Active Directory

Organizational unit

Represented by the OP. This container object is used to build a hierarchy of containers containing other objects

User

Represents a user account. The object contains a large number of attributes that describe the user

Represents a non-domain member user. Contacts are used to store information about external users in the directory; they are not accounts and do not allow users to register with the domain

Represents a group of users and is typically used to simplify the management of permissions and privileges

Computer

Represents a single computer on a local network. For computers running Windows NT, 2000, and later versions of Windows, this is the computer account. The object contains basic information about the computer and allows you to manage it

Domain controller

Represents a single Windows domain controller. In Active Directory Users and Computers, domain controllers display the same icons as regular computers. This icon is used to display domain controllers in Active Directory Sites and Services. Allows you to manage domain controller settings

Represents a network printer. The object is a link to a shared printer. Objects of this type can be added to the catalog either manually or automatically. Manual addition is only possible for printers connected to computers running versions earlier than Windows 2000

Shared resource

Represents a shared folder. The object is a link to a network share and does not contain any data

Licensing Options

Represents global site licensing settings. Allows you to centrally manage licenses for software products and their replication within the site

Domain Policy

Represents a domain policy object. Allows you to configure domain level policy settings

Domain Controller Policy

Represents a domain controller policy object. Allows you to configure policy settings for all domain controllers

Group Policy

Represents a custom GPO. Allows you to manage policy settings for objects of the container to which the policy is applied.

Represents a single Active Directory site. Allows you to manage its parameters. Contains links to domain controller objects, site links, site settings

Compound

Represents the connection between domain controllers within a site. Allows you to manage the topology and replication settings between domain controllers within a site

Site link

Represents a single link between sites. Allows you to manage the topology and parameters of intersite replication

Site settings

Represents a site or domain controller configuration object in a site. Allows you to manage replication settings for the entire site or settings for how a domain controller interacts with the site

Represents a single subnet associated with a specific site. Allows you to specify the boundaries of the IP network

Icon

An object

Description

Reboot the server.

Enter the password for directory service recovery mode.

Confirm folder locations for saving AD files.

Confirm the NetBIOS domain name.

7. Select the security level for users and groups:

· Permissions compatible with pre-Windows 2000 server– if the domain contains programs or services running on servers running Windows NT, or the computer is part of a domain running Windows NT.

· Permissions compatible only with Windows 2000 server and Windows Server 2003– if only servers running Windows 2000 server and Windows Server 2003 are running in the domain.

Active Directory administration uses a set of Active Directory management snap-ins. It consists of four equipment:

1 Active Directory User and Computers – designed for administering domain user and computer accounts.

2 Active Directory Domains and Trusts - used to establish trust relationships between domains.

3 Active Directory Sites and Service (sites and services) - designed to manage sites and site links.

4 DNS – administration of a DNS server integrated into Active Directory.

Active Directory users and computers.

Active Directory user accounts and computer accounts are physical objects just like a computer or user. User accounts can also be used as dedicated service entries for some applications.

User account– an Active Directory object containing all information that identifies a user in the Windows operating system. This information includes:

· personal data of the user (full name, phone number, e-mail, postal address, information about the organization);

· account settings (username and password required for user login, account expiration date, password management, encryption and authentication options);

· names of groups of which the user is a member;

· user profile (contains information about user-specific settings, such as desktop settings, persistent network connections, and application settings);

· other information (Terminal Services profile, remote control, session management, etc.).

Computer account- an Active Directory object that uniquely identifies a computer in a domain. The computer account corresponds to the computer name in the domain. A computer whose account has been added to a domain can participate in network operations that use Active Directory content. For example, a workstation added to a domain is able to recognize accounts and groups that exist in Active Directory.



@Computers running Windows 95, Windows 98, and Windows Me do not have additional security features and cannot be assigned computer accounts.

Group is a family of user and computer accounts, contacts, and other groups that can be managed as a single unit. Users and computers that belong to a particular group are called group members. Groups in Active Directory are directory objects that reside within domain and organizational unit container objects.

Groups in Active Directory allow you to:

· Simplify administration by assigning share permissions to a group rather than to individual users. This ensures equal access to the resource for all members of that group;

· delegate administration by assigning rights to users for the entire group at once through group policy and then adding the necessary members to the group, which must have the same rights as the group;

Groups are characterized by their scope and type. The scope of a group defines the range to which the group applies within a domain or forest. There are three different scopes: universal, global and domain local.

· Local domain (local embedded)– Members of domain-local groups can include other groups and accounts from Windows Server 2003, Windows 2000, or Windows NT domains, and can only be granted permissions within the domain.

@ Domain local groups should be used to control access to resources within the same domain.

· Global– Members of globally scoped groups can include other groups and accounts only from the domain in which the group is defined, and they can be granted permissions in any domain in the forest.

@ Globally scoped groups are recommended for managing directory objects that require daily maintenance. These include, for example, user and computer accounts. Because globally scoped groups do not replicate outside their domain, the accounts contained in such groups can be changed frequently without causing the additional traffic associated with replication to the global catalog.

· Universal- Members of universally scoped groups can include other groups and accounts from any domain in the domain tree or forest, and they can be granted permissions in any domain in the domain tree or forest.

@ Assign a universal scope to groups that span domains. To do this, add accounts to groups with global scope, and then nest those groups into groups with universal scope. With this approach, changing membership in globally scoped groups does not affect universally scoped groups.


The group type determines whether the group can be used to assign permissions to resources or only to email distribution lists.

Security groups– provide effective control of access to network resources. Using security groups allows you to do the following:

· Assign user rights to a security group in Active Directory. User rights set for security groups determine what a member of that group can do within the scope of the domain (or forest). User rights are automatically set for security groups during Active Directory installation to help administrators define the role of administrative users in the domain. For example, a user added to the Backup Operators group in Active Directory gains the ability to back up and restore files and directories on any domain controller in the domain. You can assign user rights to a security group using Group Policy to delegate specific tasks. Care must be taken when assigning delegated tasks. An inexperienced user with too many rights in a security group can potentially cause serious damage to the network.

· Assign resource permissions to security groups. Permissions should not be confused with user rights. Permissions are set for security groups that use shared resources. Permissions determine who can access a given resource and the level of access, such as full control. Some permissions set on domain objects are automatically set to different levels of access for default groups, such as Account Operators or Domain Operators. For more information about permissions, see Controlling Access in Active Directory.

@Security groups are listed in selective access control tables, which define permissions on resources and objects. Administrators should assign permissions for resources (file shares, printers, etc.) to security groups rather than to individual users. Permissions are assigned to a group once, instead of assigning rights to each individual user. Each account, when added to a group, receives the rights assigned to that group in Active Directory and the permissions defined for that group on the resource.

Distribution groups– Used only by email applications to send email messages to groups of users. Distribution groups do not use security, in other words, they cannot be included in selective access control tables (DACLs). If a group is created to control access to shared resources, the group must be a security group.

@Security groups can also be used as email destinations, just like distribution groups. An email message sent to a group is sent to all members of the group.

There are also groups for which you cannot edit or view membership information. These groups are called special identities and are used to represent different users at different times, depending on the circumstances.

(Anonymous Login, All, Network, Interactive)

For example, the Everyone group represents all current network users, including guests and users from other domains. For more information, see Special Identities.

User and computer accounts (and groups) are called security principals. Security principals are directory objects that are automatically assigned security IDs (SIDs) to access domain resources. A user or computer account is used for the following purposes:

· user or computer authentication.

· allowing or denying access to domain resources.

· administration of other security principals (to represent a security principal from an external trusted domain).

· audit of actions performed using a user account or computer.

To assign rights simultaneously a large number security groups are used for users. Accounts can be grouped using organizational units (containers).

To ensure secure user authentication, you should create separate accounts for each network user using the " Active Directory users and computers ».

Each Active Directory user account has a number of security-related settings that determine how the account is authenticated when logging on to the network.

Dedicated to using PowerShell to administer AD. As a starting point, the author decided to take 10 common AD administration tasks and look at how they can be simplified using PowerShell:

  1. Reset user password
  2. Activate and deactivate accounts
  3. Unlock user account
  4. Delete your account
  5. Find empty groups
  6. Add users to a group
  7. List group members
  8. Find outdated computer accounts
  9. Deactivate a computer account
  10. Find computers by type

In addition, the author maintains a blog (using PowerShell, of course), we recommend taking a look - jdhitsolutions.com/blog. And you can get the most up-to-date information from his Twitter twitter.com/jeffhicks.
So, below is the translation of the article “Top 10 Active Directory Tasks Solved with PowerShell”.

Managing Active Directory (AD) using Windows PowerShell is easier than you think, and I want to prove it to you. You can simply take the scripts below and use them to solve a number of AD management tasks.

Requirements

To use PowerShell to manage AD, you need to meet several requirements. I'm going to demonstrate how the AD cmdlets work using a Windows 7 computer as an example.
To use the cmdlets, you must have a Windows Server 2008 R2 domain controller, or you can download and install Active Directory Management Gateway Service on legacy DCs. Please read the documentation carefully before installation; CD reboot required.
On the client side, download and install (RSAT) for either Windows 7 or Windows 8. On Windows 7, you will need to open in Control Panels chapter Programs and choose Turn Windows Features On or Off. Find Remote Server Administration Tools and expand the section Role Administration Tools. Select the appropriate items for AD DS and AD LDS Tools, especially note that the item must be selected Active Directory Module for Windows PowerShell, as shown in Figure 1. (In Windows 8, all tools are selected by default). Now we are ready to work.

Fig.1 Enabling AD DS and AD LDS Tools

I am logged in with an account with domain administrator rights. Most of the cmdlets I'll show will allow you to specify alternative credentials. In any case, I recommend reading the help ( Get-Help) and examples that I will demonstrate below.
Start a PowerShell session and import the module:

PS C:\> Import-Module ActiveDirectory

The import creates a new PSDrive, but we won't be using it. However, you can see what commands are available in the imported module.

PS C:\> get-command -module ActiveDirectory

The beauty of these commands is that if I can use a command on one AD object, then it can be used on 10, 100, and even 1000. Let's see how some of these cmdlets work.

Task 1: Reset the user password

Let's start with a typical task: resetting a user's password. You can do this easily and simply using a cmdlet Set-ADAccountPassword. The tricky part is that the new password must be qualified as a protected string: a piece of text that is encrypted and stored in memory for the duration of the PowerShell session. First, let's create a variable with the new password:
PS C:\> $new=Read-Host "Enter the new password" -AsSecureString

Then, enter a new password:

Now we can extract the account (using samAccountnamethe best option) and set a new password. Here's an example for user Jack Frost:

PS C:\> Set-ADAccountPassword jfrost -NewPassword $new

Unfortunately, there is a bug with this cmdlet: -Passthru, -Whatif, And –Confirm does not work. If you prefer a shortcut, try this:

PS C:\> Set-ADAccountPassword jfrost -NewPassword (ConvertTo-SecureString -AsPlainText -String "P@ssw0rd1z3" -force)

As a result, I need Jack to change his password the next time he logs in, so I modify the account using Set-ADUser.

PS C:\> Set-ADUser jfrost -ChangePasswordAtLogon $True

The results of running the cmdlet are not written to the console. If this needs to be done, use –True. But I can find out whether the operation was successful or not by retrieving the username using the cmdlet Get-ADUser and specifying the property Password Expired, as shown in Figure 2.


Rice. 2. Results of the Get-ADUser Cmdlet with the PasswordExpired property

Bottom line: Resetting a user's password using PowerShell is not difficult at all. I admit that resetting the password is also easy through the snap Active Directory Users and Computers consoles Microsoft Management Console (MMC). But using PowerShell is appropriate if you need to delegate a task, don't want to deploy the above-mentioned snap-in, or are resetting a password as part of a large automated IT process.

Task 2: Activate and deactivate accounts

Now let's deactivate the account. Let's continue working with Jack Frost. This code uses the parameter –Whatif, which you can find in other comadlets that make changes to test my command without running it.

PS C:\> Disable-ADAccount jfrost -whatif What if: Performing operation "Set" on Target "CN=Jack Frost, OU=staff,OU=Testing,DC=GLOBOMANTICS,DC=local".

Now let’s deactivate it for real:

PS C:\> Disable-ADAAccount jfrost

And when the time comes to activate the account, which cmdlet will help us?

PS C:\> Enable-ADAccount jfrost

These cmdlets can be used in a pipelined expression, allowing you to activate or deactivate as many accounts as you like. For example, this code will deactivate all accounts in the Sales department

PS C:\> get-aduser -filter "department -eq "sales"" | disable-adaccount

Of course, write a filter for Get-ADUser quite complicated, but this is where the use of the parameter –Whatif along with the cmdlet Disable-ADAccount comes to the rescue.

Task 3: Unlock the user account

Consider a situation where Jack locked out his account while trying to enter a new password. Instead of trying to find his account through the GUI, the unlocking procedure can be done using a simple command.

PS C:\> Unlock-ADAAccount jfrost

The cmdlet also supports parameters -Whatif And -Confirm.

Task 4: Delete account

It doesn't matter how many users you remove - it's easy to do using the cmdlet Remove-ADUser. I don't want to remove Jack Frost, but if I wanted to, I would use code like this:

PS C:\> Remove-ADUser jfrost -whatif What if: Performing operation "Remove" on Target "CN=Jack Frost,OU=staff,OU=Testing,DC=GLOBOMANTICS,DC=local".

Or I can enter multiple users and delete them with one simple command:

PS C:\> get-aduser -filter "enabled -eq "false"" -property WhenChanged -SearchBase "OU=Employees, DC=Globomantics,DC=Local" | where ($_.WhenChanged -le (Get-Date).AddDays(-180)) | Remove-ADuser -whatif

This command will find and delete any disabled Employees OU accounts that have not been modified for 180 days or more.

Task 5: Finding empty groups

Managing groups is an endless and thankless task. There are many ways to find empty groups. Some expressions may work better than others, depending on your organization. The code below will find all groups in the domain, including built-in ones.

PS C:\> get-adgroup -filter * | where (-Not ($_ | get-adgroupmember)) | Select Name

If you have groups with hundreds of members, then using this command can take a long time; Get-ADGroupMember checks each group. If you can limit or customize it will be better.
Here's another approach:

PS C:\> get-adgroup -filter "members -notlike "*" -AND GroupScope -eq "Universal"" -SearchBase "OU=Groups,OU=Employees,DC=Globomantics, DC=local" | Select Name,Group*

This command finds all Universal groups that do not have membership in OU Groups and displays some of the properties. The result is shown in Figure 3.


Rice. 3. Search and filter universal groups

Task 6: Adding users to a group

Let's add Jack Frost to the Chicago IT group:

PS C:\> add-adgroupmember "chicago IT" -Members jfrost

Yes, it's that simple. You can also easily add hundreds of users to groups, although I find this a little awkward:

PS C:\> Add-ADGroupMember "Chicago Employees" -member (get-aduser -filter "city -eq "Chicago"")

I used the parenthetical pipelined expression to find all users who have the City property in Chicago. The code in parentheses is executed and the resulting objects are passed to the –Member parameter. Each user object is added to the Chicago Employees group. It doesn't matter whether we are dealing with 5 or 5000 users, updating group memberships takes just a few seconds. This expression can also be written using ForEach-Object what might be more convenient:

PS C:\> Get-ADUser -filter "city -eq "Chicago"" | foreach (Add-ADGroupMember "Chicago Employees" -Member $_)

Task 7: List group members

You might want to know who is in a certain group. For example, you should periodically find out who is a member of the Domain Admins group:

PS C:\> Get-ADGroupMember "Domain Admins"

Figure 4 shows the result.


Rice. 4. Members of the Domain Admins group

The cmdlet displays the AD object for each group member. What to do with nested groups? My group Chicago All Users is a collection of nested groups. To get a list of all accounts, I just have to use the parameter –Recursive.

PS C:\> Get-ADGroupMember "Chicago All Users" -Recursive | Select DistinguishedName

If you want to go the other way - find which groups a user is in - use the user property MemberOf:

PS C:\> get-aduser jfrost -property Memberof | Select -ExpandProperty memberOf CN=NewTest,OU=Groups,OU=Employees, DC=GLOBOMANTICS,DC=local CN=Chicago Test,OU=Groups,OU=Employees, DC=GLOBOMANTICS,DC=local CN=Chicago IT,OU= Groups,OU=Employees, DC=GLOBOMANTICS,DC=local CN=Chicago Sales Users,OU=Groups,OU=Employees, DC=GLOBOMANTICS,DC=local

I used the parameter -ExpandProperty to display names MemberOf like lines.

Task 8: Find outdated computer accounts

I get asked this question a lot: “How do I find outdated computer accounts?” And I always answer: “What is outdated for you?” Companies have different definitions of when a computer account (or user account, it doesn't matter) is considered obsolete and can no longer be used. For me, I pay attention to those accounts whose passwords have not been changed for a certain period of time. This period for me is 90 days - if the computer has not changed the password along with the domain during this period, most likely it is offline and outdated. Cmdlet used Get-ADComputer:

PS C:\> get-adcomputer -filter "Passwordlastset -lt "1/1/2012"" -properties *| Select name,passwordlastset

The filter works great with a hard value, but this code will update for all computer accounts that have not changed their passwords since January 1, 2012. The results are shown in Figure 5.


Rice. 5. Find outdated computer accounts

Another option: let's assume you are at least at the Windows 2003 domain functional level. Filter by property LastLogontimeStamp. This value is the number of 100 nanosecond intervals since January 1, 1601, and is stored in GMT, so working with this value is a little tricky:

PS C:\> get-adcomputer -filter "LastlogonTimestamp -gt 0" -properties * | select name,lastlogontimestamp, @(Name="LastLogon";Expression=(::FromFileTime ($_.Lastlogontimestamp))),passwordlastset | Sort LastLogonTimeStamp


Rice. 6. Convert the LastLogonTimeStamp value to a familiar format

To create a filter, I need to convert the date, for example January 1, 2012, into the correct format. Conversion is carried out in FileTime:

PS C:\> $cutoff=(Get-Date "1/1/2012").ToFileTime() PS C:\> $cutoff 129698676000000000

Now I can use this variable in the filter to Get-ADComputer:

PS C:\> Get-ADComputer -Filter "(lastlogontimestamp -lt $cutoff) -or (lastlogontimestamp -notlike "*")" -property * | Select Name,LastlogonTimestamp,PasswordLastSet

The above code finds the same computers that were shown in Figure 5.

Task 9: Deactivate the computer account

Perhaps when you find inactive or outdated accounts, you will want to deactivate them. This is quite easy to do. We will use the same cmdlet that we used to work with user accounts. You can clarify it by using samAccountname account.

PS C:\> Disable-ADAccount -Identity "chi-srv01$" -whatif What if: Performing operation "Set" on Target "CN=CHI-SRV01, CN=Computers,DC=GLOBOMANTICS,DC=local".

Or using a pipeline expression:

PS C:\> get-adcomputer "chi-srv01" | Disable-ADAccount

I can also use my code to find outdated accounts and deactivate them all:

PS C:\> get-adcomputer -filter "Passwordlastset -lt "1/1/2012"" -properties *| Disable-ADAccount

Task 10: Find computers by type

I also often get asked how to find computer accounts by type, such as servers or workstations. This requires some creativity on your part. There is nothing in AD that distinguishes a server from a client, except perhaps the OS. If your computer is running Windows Server 2008, you will have to do a few extra steps.
First, you need to get a list of operating systems, and then we filter accounts by available operating systems.

PS C:\> Get-ADComputer -Filter * -Properties OperatingSystem | Select OperatingSystem -unique | Sort OperatingSystem

The results are shown in Figure 7.


Rice. 7. Retrieving the OS list

I want to find all computers running a server OS:

PS C:\> Get-ADComputer -Filter "OperatingSystem -like "*Server*"" -properties OperatingSystem,OperatingSystem ServicePack | Select Name,Op* | format-list

The results are shown in Figure 8.

Like other AD Get cmdlets, you can customize search parameters and limit the request to specific OUs if necessary. All the expressions I've shown can be integrated into larger PowerShell expressions. For example, you can sort, group, apply filters, export to CSV, or create and email HTML reports - all from PowerShell! In this case, you won’t have to write a single script.
Here's a bonus: a user password-age report, saved in an HTML file:

PS C:\> Get-ADUser -Filter "Enabled -eq "True" -AND PasswordNeverExpires -eq "False"" -Properties PasswordLastSet,PasswordNeverExpires,PasswordExpired | Select DistinguishedName,Name,pass*,@(Name="PasswordAge"; Expression=((Get-Date)-$_.PasswordLastSet)) |sort PasswordAge -Descending | ConvertTo-Html -Title "Password Age Report" | Out-File c:\Work\pwage.htm !}

Although this expression may look a little intimidating, it is easy to use with minimal knowledge of PowerShell. And only one last piece of advice remains: how to define a custom property called PasswordAge. The value represents the gap between today and the PasswordLastSet property. Then I sort the results for my new property. Figure 9 shows the output for my small test domain.

Upd:
The post contains a translation of the article on the portal

Those who have had to deal with things like an Excel spreadsheet listing 200 new employees starting next week, or user accounts configured incorrectly because someone in Help Desk clicked something they shouldn't have clicked, and Also, those who are interested in an easier way to manage Active Directory®, in addition to opening the Users and Computers folders every time, can use one of the free administration tools. Some of them are built right into operating system Windows, some are provided in the Resource Kit or Windows Support Toolkit, and some are free third-party products. What are these convenient products and where can I get them? Let's find out.
Let's start with the built-in command line tools in Windows Server 2003 that let you create, delete, modify, and search objects in Active Directory.

The CSVDE tool allows you to import new objects into Active Directory using the original CSV file; it also provides the ability to export existing objects to a CSV file. CSVDE cannot be used to modify existing objects; When using this tool in import mode, you can only create new objects.

Exporting a list of existing objects using CSVDE is quite simple. The following shows how to export Active Directory objects to a file called ad.csv:

csvde –f ad.csv

The -f option specifies that it is followed by the name of the output file. But be aware that, depending on your environment, this basic syntax can result in a huge and inconvenient file output. To limit the tool to exporting only objects within a specific organizational unit (OU), the command can be modified as follows:

csvde –f UsersOU.csv –d ou=Users,dc=contoso,dc=com

Let's further assume that I only need to export user objects to my CSV file. In this case, you can add the –r option to specify an LDAP protocol filter for this search, which will limit the number of attributes exported (note that the following is all on one line):

csvde –f UsersOnly.csv –d ou=Users,dc=contoso,dc=com –r
"(&(objectcategory=person)(objectclass=user))" –l
DN,objectClass,description

The –i option allows you to import objects into Active Directory from a CSV source file. However, creating user objects with CSVDE has one important drawback: it cannot set user passwords, so I would not use CSVDE to create user objects.

Active Directory provides a second built-in user batch operation called LDIFDE, which is more powerful and flexible than CSVDE. In addition to creating new objects, LDIFDE allows you to modify and delete existing objects and even extend the Active Directory schema. The trade-off for LDIFDE's flexibility is that the required input file (an LDIF file) with a .ldf extension uses a more complex format than a simple CSV file. (With a little work, you can also configure user passwords, but more on that later.)

Let's start with a simple example - exporting users in a business unit to an LDF file (note that the following is all on one line):

ldifde -f users.ldf -s DC1.contoso.com -d "ou=UsersOU,dc=contoso,dc=com"
–r "(&(objectcategory=person)(objectclass=user))"

As with most command line tools, a complete description of the LDIFDE options can be obtained by running the LDIFDE /? . shown are the ones I used here. (Note that the parameters for the CSVDE and LDIFDE commands are the same.)

The real power of LDIFDE comes from creating and managing objects. However, before doing this, you need to create an input file. The following code creates two new user accounts - afuller and rking; To create an input file, enter the text in Notepad (or another plaintext editor) and save it as NewUsers.ldf:

dn: CN=afuller, OU=UsersOU, DC=contoso, DC=com
changetype: add
cn: afuller
objectClass: user
samAccountName: afuller dn: CN=rking, OU=UsersOU, DC=contoso, DC=com
changetype: add
cn:rking
objectClass: user
samAccountName: rking

Once the file creation is complete, run the following command:

ldifde –i –f NewUsers.ldf –s DC1.contoso.com

The only new option here is -i, which, as you might guess, specifies that the operation is importing rather than exporting.

When modifying or deleting existing objects, the syntax of the LDIFDE command does not change; instead, the contents of the LDF file are modified. To modify the user account description field, create a text file called ModifyUsers.ldf, such as the one shown in Figure. 2.


Rice. 2 LDF File ModifyUsers

Changes are imported by running the same LDIFDE command syntax as before, specifying the new LDF file after the -f option. The LDF format for deleting objects is even simpler; To delete users you have worked with, create a file called DeleteUsers.ldf and enter the following:

dn: CN=afuller OU=UsersOU, DC=contoso, DC=com
changetype: delete dn: CN=rking, OU=UsersOU, DC=contoso, DC=com
changetype: delete

Note that, unlike CSVDE, LDIFDE can configure user passwords. However, before you can configure the unicodePWD attribute on a user account, you must configure SSL/TLS encryption on your domain controllers. In addition, LDIFDE can create and modify any Active Directory objects, not just user accounts. For example, the following LDF file will create a new schema extension called EmployeeID-example in the contoso.com forest schema:
dn: cn=EmployeeID-example,cn=Schema,
cn=Configuration,dc=contoso,dc=com
changetype: add
adminDisplayName: EmployeeID-Example
attributeID: 1.2.3.4.5.6.6.6.7
attributeSyntax: 2.5.5.6
cn: Employee-ID
instanceType: 4
isSingleValued: True
lDAPDisplayName: employeeID-example

Because LDIFDE files use the industry standard LDAP file format, third-party applications that need to modify the Active Directory schema often supply LDF files that can be used to review and approve the changes before applying them to the production environment.

In addition to tools for batch import and export operations, Windows Server 2003 includes built-in tools that allow you to create, delete, and modify various Active Directory objects, as well as query objects that meet certain criteria. (Note that these tools, dsadd, dsrm, dsget, and dsquery, are not supported by Active Directory on Windows 2000.)

Dsadd is used to create an instance of an Active Directory object class in a specific directory partition. These classes include Users, Computers, Contacts, Groups, Business Units, and Quotas. Note that each type of object created requires a special set of parameters that correspond to the attributes available for that type. This command creates a single user object with various attributes populated (note that the following is all on one line):

dsadd user cn=afuller,ou=IT,dc=contoso,dc=com
–samID afuller –fn Andrew –ln Fuller –pwd *
-memberOf cn=IT,ou=Groups,dc=contoso,dc=com "cn=Help Desk,ou=Groups,
dc=contoso,dc=com"
–desc "Marketing Director"
The -memberOf parameter requires the fully qualified distinguished name (DN) of each group to which the user should be added; if you need to add the user to multiple groups, you can add multiple DNs separated by spaces. If an element, say the DN of the Help Desk group, contains a space, this The element must be placed in double quotes. If an element, say the IT\EMEA business unit, contains a backslash, you must enter the backslash twice: IT\\EMEA. (These requirements apply to all ds* tools.) Using the -pwd * option will prompt you to enter a password for the user at the command line. The password can be specified within the command itself (-pwd P@ssword1), but then it will be displayed in clear text on the screen or in any text or script file into which the command is inserted.

Similarly, you can create a group object and a business unit using the following two commands:

dsadd computer cn=WKS1,ou=Workstations,dc=contoso,dc=com
dsadd ou "ou=Training OU,dc=contoso,dc=com"

Dsmod is used to modify existing objects, and is worked in much the same way as dsadd, using different submenus and syntax depending on the type of object being modified. The following dsmod command changes the user's password and modifies their account so that they are prompted to change their password the next time they log on:

dsmod user "cn=afuller,ou=IT,dc=contoso,dc=com" –pwd P@ssw0rd1
–mustchpwd yes

To see how similar these options are, take a look at the dsadd syntax used to create a user with the same attributes configured:

dsadd user "cn=afuller,ou=IT,dc=contoso,dc=com" –pwd P@ssw0rd1
–mustchpwd yes

Obviously, if you know the parameters for creating objects using dsadd, you can use them to change users using dsmod.

The opposite of dsadd is dsrm; As you might imagine, this tool is used to remove objects from the command line. The basic syntax for dsrm is fairly straightforward: just type dsrm followed by the distinguished name of the object you want to delete, something like this:

dsrm cn=WKS1,ou=Workstations,dc=contoso,dc=com

By default, dsrm will ask "Are you sure you want to delete this object?" Type Y and press Enter. This request can be disabled using the –noprompt parameter, but, obviously, in this case, the chance to confirm that the object was selected correctly before deleting will disappear. Two additional options can be useful when deleting a container object, that is, a structural unit that could potentially contain other objects. The following command deletes the TrainingOU organizational unit and all objects it contains:

And this one deletes all child objects in TrainingOU, but does not touch the structural unit itself:

dsrm ou=TrainingOU,dc=contoso,dc=com –subtree
–exclude

You can use the dsmove tool to move or rename an object in Active Directory, but note that it can only be used to move objects within a domain. To migrate objects between domains or forests, use the Active Directory Migration Tool (ADMT), a free download from Microsoft. Dsmove relies on two parameters, which can be used separately or together. This command changes the last name on the Steve Conn user account:

dsmove "cn=Conn, Steve,ou=IT,dc=contoso,dc=com"
–newname "Steve Conn"

This command moves the Steve account from the IT organizational unit to the Training organizational unit:

dsmove "cn=Conn, Steve,ou=IT,dc=contoso,dc=com" –newparent
ou=Training,dc=contoso,dc=com

Renaming and transfer can be done in one operation by specifying both parameters at once:

dsmove "cn=Conn, Steve,ou=IT,dc=contoso,dc=com" –newname
"Steve Conn" –newparent ou=Training,dc=contoso,dc=com

Dsget and Dsquery

The ds* command-line tools also include two tools that are used to query Active Directory information rather than to create or modify objects.

Dsget takes as input the distinguished name (DN) of an object and returns the value of the specified attribute or attributes. Dsget uses the same submenus as dsadd and dsmod - "user", "computer", "contact", "group", "division" and "quota".

To get the SAM account name and security ID (SID) of the user account, enter the following command (note that the following is all on one line):

dsget user cn=afuller,ou=IT,dc=contoso,dc=com
–samAccountName –sid

The results will be similar to those shown in Fig. 3.

Rice. 3 How dsget works

Dsquery returns a list of Active Directory objects that match the specified criteria.

Dsquery can use the following submenus, each with its own syntax, for ObjectType: "computer", "contact", "subnet", "group", "business unit", "website", "server" (note that the submenu Server retrieves data about domain controllers, not servers in your environment), "user", "quota" and "partition". And if one of these query types is not what you need, you can use the * submenu to enter a free-form LDAP query. StartNode specifies the location of the Active Directory tree where the search will begin. You can use a specific DN, such as ou=IT,dc=contoso,dc=com, or one of the following short path descriptors: domainroot, starting at the root of a specific domain, or forestroot, starting at the root of the forest root domain, using a global catalog server to perform a search. Finally, the search scope parameter specifies how dsquery should search the Active Directory tree. Subtree surveys (the default option) access the specified StartNode and all of its children, sibling surveys access only the immediate children of the StartNode, and base surveys access only the StartNode object. To better understand search scopes, imagine an organizational unit (OU) containing both user objects and a child OU, which also contains additional objects. When using a subtree as the scope, the OU, all user objects within it, the child OU, and its contents will be queried. With a single-level scope, only the users contained in the OU will be queried, but not the child OU and its contents. A basic query will only query the OU itself, without querying the objects it contains. Finally, you can use the output format to control how the dsquery results are formatted. By default, dsquery returns the distinguished names of all objects that match the query, something like this:

"cn=afuller,ou=Training,dc=contoso,dc=com"
"cn=rking,ou=ITTraining,ou=Training,dc=contoso,dc=com" To query all user objects contained in an IT business unit and its child OUs, use the following:

dsquery user ou=IT,dc=contoso,dc=com

The query can be made even more precise by adding additional options, such as -disabled, which returns only disabled user accounts; -inactive x, returning only users who have not connected for x or more weeks; or -stalepwd x, returning only users who have not changed their passwords for x days or more.

Depending on the number of objects in the directory, you may need to specify the -limit x option when running the query. By default, dsquery returns up to 100 objects matching the query parameters; but you can specify a larger number, such as -limit 500, or use -limit 0 to have dsquery return all matching objects.

You can also use other submenus to perform useful queries on other types of objects. Consider the following query, which returns each subnet defined in Active Directory Sites and Services and included in the 10.1.x.x address space:

dsquery subnet –name 10.1.*

And the following command can be used to return each subnet located on the Corp website:

dsquery subnet –site Corp

Using the next submenu, you can quickly determine how many domain controllers in the forest are configured to work as global catalog servers:

dsquery server –forest –isgc

You can also use this syntax to make it easier to identify a domain controller in a specific domain that contains the FSMO role of the primary domain controller (PDC) emulator:

dsquery server –hasfsmo pdc

As with other ds* commands that include submenus, all options available in a particular dsquery submenu can be viewed by entering command line and entering dsquery user /?, dsquery computer /?, dsquery subnet /?, and so on.

An additional trick is to pipe the outgoing dsquery data to another tool, such as dsmod, using the | (SHIFT+backslash for English keyboard layout). For example, a company has renamed a department from “Training” to “Internal Development”, and now needs to update the description field for each user belonging to this department. With one command line, you can query all user objects that have a Provisioning description field, and then replace that description field for the entire package as follows:

dsquery user –description "Training" | dsmod
-description "Internal Development"

Some third-party finds

Because Active Directory is based on LDAP standards, you can query and make changes to it using any tool that understands LDAP. Many third-party vendors have released paid tools to help with Active Directory administration, but sometimes you can find real gems that are free. This is particularly true of the collection created by directory services MVP Joe Richards and available for download at joeware.net/freetools. In it you can find numerous tools that serve to solve various problems. Three of them I return to constantly are adfind, admod and oldcmp.

Adfind and Admod

Adfind and admod are similar to dsquery and dsmod; adfind is a command line query tool for Active Directory, and admod can create, delete, or modify Active Directory objects.

Unlike the ds* tools, which have multiple submenus and different options depending on the type of object, adfind and admod use the same syntax regardless of the type of query or change being performed. The basic syntax for adfind is:

adfind –b -s -f
attributesDesired

A query for the distinguished name and description of all computer objects in a domain would look like:

adfind –b dc=contoso,dc=com –s subtree –f (objectclass=computer) dn
description

A query for all user objects would look like:

adfind –b dc=contoso,dc=com –s subtree –f "(&(objectcategory=person)
(objectclass=user))" dn description

Note that except for querying the LDAP content, the syntax has not changed.

When working with adfind, you can find several shortcuts for writing parameters that eliminate unnecessary typing work. For example, the -default option could replace -b dc=contoso,dc=com in the previous example and search the entire domain; -gc searches based on garbage collection (GC) and returns all users in your Active Directory forest. The -rb option can also be used to set the relative base for the search; if, say, you need to find the “Training” structural unit in the phl.east.us.contoso.com domain, then you can significantly save time by simply specifying –default –rb ou=Training, instead of –b ou=Training, dc=phl, dc=east,dc=us,dc=contoso,dc=com.

Adfind can also perform a number of advanced search functions that are difficult to manage from the command line without it.

An example using the -asq option would request "Show me the group memberships of HelpDesk members" like this:

adfind –default –rb cn=HelpDesk,ou=IT –asq member memberOf

Admod, as the name of the program suggests, is used to modify objects in Active Directory. As with adfind, there are no specialized submenus with their own syntaxes that you need to remember; admod uses the same syntax regardless of the type of object being processed. Admod can also be used to add, move, rename, delete, and even restore objects by simply adding the appropriate option, say -add, -rm, -move, -undel. And just like in dsquery and dsmod, the | can be used to pipe adfind request data to admod.

Note that performing a restore using admod is a simple operation of restoring a tombstone object in which most of the object's attributes have already been removed. To completely restore an object with all attributes, you will need to perform a forced restoration of the object.

There is another tool from Joe's collection of programs that I consider an essential part of my automation toolkit: oldcmp, which searches the Active Directory database for the credentials of computers that have not been used for a specified number of weeks and can do the following:

  • create reports on accounts without taking any action on them;
  • disable unused computer accounts;
  • move computer accounts to another, pre-specified structural unit;
  • completely delete computer accounts.

I note that since oldcmp can cause serious directory havoc, it comes with several built-in security features. It doesn't delete accounts that weren't previously disabled (unless you said "No, I really want to do this!" on the command line). It does not modify more than 10 objects at a time (unless, again, specifically stated otherwise), and it will never do anything to the domain controller's computer account.

Joe has now updated oldcmp so that it can also perform similar functions on user accounts that have not been used for a specified period of time.

For a small Active Directory environment, or one where you are working with only one or two additions or changes at a time, GUI tools such as Active Directory Users and Computers may be sufficient for day-to-day administration, but need to be added on a daily basis. or changing a large number of objects or simply wanting to find a more efficient solution for administrative tasks, switching to the command line can greatly speed up the process of creating, changing and deleting objects in Active Directory. As shown above, there are a number of flexible and powerful free tools available, both built into Windows and distributed by members of the Active Directory community. Any one of them can greatly improve the productivity of an Active Directory administrator, and together they become even more important to his daily work.

Laura E. Hunter is a four-time Microsoft MVP for Windows Server Networking Tools. She is the author of the second edition of the Active Directory Reference Guide (O'Reilly, 2006). With ten years of experience in the IT industry, Laura now works as an Active Directory designer for a world-class engineering firm. She also holds several industry certifications. certifications and is a frequent speaker at user group meetings and industry conferences.