PART I USING POWERSHELL WITH ACTIVE DIRECTORY TE D X CHAPTER 1 MA TE RI AL Administering Service Delivery MANAGING DOMAIN AND FORESTS X CHAPTER 3 MANAGING SITES AND REPLICATION X CHAPTER 4 MANAGING DOMAIN CONTROLLERS CO PY RI GH X CHAPTER 2 03 55 91 157
CHAPTER 1 Using PowerShell with Active Directory IN THIS CHAPTER, YOU WILL LEARN TO: X UNDERSTAND THE BASICS OF POWERSHELL 4 Use the Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Use the Scripting Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 Understand Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 Work with Cmdlets . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 1 S ince the dawn of the information technology age, administrators have been continually searching for ways to make their jobs easier. Rather than spending time performing the same or similar tasks repeatedly, many administrators have taken to adopting some form of automation. Throughout the years, you’ve witnessed many advances in automation, from the early days of DOS batch files to VBScripts and Windows Management Instrumentation (WMI).
return a text string as output. PowerShell is based on the .NET Framework. Rather than using text, PowerShell takes .NET objects as input and returns .NET objects as output. So, when the dir command is run, PowerShell enumerates the files and folders on disk and treats each file and folder as a separate object. Each object is composed of a variety of properties that describe it, which are exposed as the headings across the top of the output.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Use the Shell The shell is the primary way that you’ll interact with PowerShell. The shell is very similar to the Windows command prompt. You can type in commands and have some output returned to you. You can launch the shell by clicking the Start menu and selecting All Programs ‚ Accessories ‚ Windows PowerShell ‚ Windows PowerShell.
You can use the right arrow key to retype the previous command one character at a time. You also have the option of accessing a list of the previous 50 commands by pressing the F7 key, as shown in Figure 1.3. Navigate through this list by using the arrow keys and pressing Enter on the command you want to execute, or type the command number that you want to execute and press F9. To close the list without executing a command, press the Esc key.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Use the Scripting Environment PowerShell 2.0 provides a new Integrated Scripting Environment (ISE) for writing PowerShell scripts with more ease. The ISE provides some great capabilities that are typically found in expensive development environments.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L The PowerShell Integrated Scripting Environment Administering Service Delivery F I G U R E 1. 4 9 PART I Script editor Output pane Command pane N O T E It’s important to understand that the ISE isn’t the only way to create PowerShell scripts. PowerShell scripts can be created with any text editor, including built-in utilities like Notepad and WordPad, along with third-party development environments.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Profile Scripts The PowerShell profile is really a script that runs automatically when you open PowerShell. PowerShell scripts are covered in more detail later in this chapter, but for now just know that you can execute various PowerShell commands, save variables, and define functions in your PowerShell profile. For example, suppose you frequently put your computer into Hibernate mode.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L 11 Copyright (C) 2009 Microsoft Corporation. All rights reserved. Administering Service Delivery by PowerShell to ensure that only trusted scripts are run. You’ll learn how to create a trusted script later in this chapter in the “Create PowerShell Scripts” section: File C:\Users\Administrator\Documents\WindowsPowerShell\Microso PART I Windows PowerShell ft.PowerShell_profile.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Cmdlets are precompiled and can be run from the PowerShell command interpreter directly or be used in a script. They’re surprisingly flexible and can be used in a variety of ways. PowerShell has several cmdlets built in, and applications can provide their own cmdlets as well. For example, Active Directory adds 76 additional cmdlets to PowerShell when the module is installed.
example, if you want to get information about a specific service on your computer, you can run the same Get-Service cmdlet that you just ran, but this time specify the name of the service as a parameter. Figure 1.7 shows the output of the GetService cmdlet run against the Windows Update service. F I G U R E 1. 7 Adding a parameter to a cmdlet 13 Administering Service Delivery U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L PART I The -Name parameter shown in Figure 1.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Each cmdlet has a different set of parameters that it recognizes. The -ComputerName parameter in the previous example is only relevant for the Get-Service cmdlet. If you tried to pass it into the Get-ChildItem cmdlet, an error would be thrown: PS C:\> Get-ChildItem -ComputerName localhost Get-ChildItem : A parameter cannot be found that matches parameter name ‘Comput erName’.
Name Description -OutVariable Specifies a variable to which you want to write the output objects. -OutBuffer Determines how many objects are in the output buffer before the objects are passed through the pipeline. This is an advanced parameter that you probably won’t use frequently, if at all. 15 Administering Service Delivery U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L PART I N O T E Cmdlets and their parameters aren’t case sensitive.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY String Cmdlets Together When used alone, a cmdlet can be a powerful tool. However, you can use cmdlets more efficiently by stringing multiple cmdlets together using a process called pipelining. When you pipeline two cmdlets, the results from the fi rst cmdlet are fed into the second cmdlet. In order to perform a pipeline, you use the pipe character (|).
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L The output of the Get-Help cmdlet Administering Service Delivery F I G U R E 1. 8 17 PART I Various types of help are available for cmdlets. If you don’t want to read through a large screen full of text just to find out the syntax for a particular command, you can add the -Examples parameter to the Get-Help cmdlet. This will only display the examples for the cmdlet. Figure 1.9 demonstrates the output of Get-Help with the -Examples parameter.
CHAPTER 1 • TA B L E 1.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L 19 Script Administration Tasks In addition to offering a robust environment for executing cmdlets, PowerShell also provides an integrated environment for writing scripts. Like one-liners, scripts allow you to execute a series of commands all at once, without having to enter each command individually.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY When you’re done creating your script, save it with a .ps1 extension, and the script will be executable in PowerShell. Execution Policy With great power comes great responsibility. Being the robust scripting environment that PowerShell is, its capabilities could potentially be misused. There has been a lot of scripting misuse in the past with other scripting languages.
If you’re running scripts that you wrote for computer administration, then using the RemoteSigned setting will be ideal in most cases. However, you do have the option of signing the scripts that you create for additional security. If you’re going to be using PowerShell scripts for Active Directory administration and storing the scripts on a network share or somewhere that other people may have write access to, then it’s a good idea to sign the scripts.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY her private key. Bob doesn’t manually validate Alice’s script against her public key, however. This process is handled by PowerShell when Bob attempts to run the script. To be able to sign scripts, you first need to obtain a code-signing certificate with a private key. This certificate must be trusted by the computer that the script is executing on in order for it to be considered valid.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L 23 makecert.exe -r -pe -n “CN=PowerShell Signing Cert” -ss MY -a sha1 -eku i 1.3.6.1.5.5.7.3.3 You can then run the following PowerShell command to verify that the certificate was successfully created: PS C:\> Get-ChildItem cert:\currentuser\my -codesigning Directory: Microsoft.PowerShell.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY N O T E Some other development languages require you to define what kind of data your variables will hold up front, but this isn’t the case with PowerShell. Variables in PowerShell all begin with a dollar sign ($).
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L Listing the currently used variables Administering Service Delivery F I G U R E 1.10 25 PART I In addition to variables that you define yourself, there are special variables called shell variables built into PowerShell. Shell variables are automatically created by PowerShell. An example of a shell variable is $null, which always means that something has no value.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Add Logic to a Script Logic allows your scripts to do things to the variables you’re using and make decisions about what to do. You need to know two basic logic concepts in order to write PowerShell scripts: loops and conditionals. Loops Loops allow you to go through a collection of items and do something to each item.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L 27 Current Number: 0 Current Number: 1 Current Number: 2 The Do statement loops through the code inside the curly brackets for as long as the condition specified in the While statement is valid. In this example, the Do loop will keep going as long as the $counter variable is less than 3 (-lt 3). After $counter reaches 3, the loop stops, and therefore only the numbers 0, 1, and 2 are displayed. With a Do ...
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY statement can either end or test to see if something else is true. For example, consider the following If statement: $RunningProcesses = Get-Process $RunningProcesses | ForEach-Object { $MemUsageMB = $_.PrivateMemorySize / 1024 / 1024 If ($MemUsageMB -lt 50) { Write-Host $_.Name “: Using less than 50MB of memory” } Else { Write-Host $_.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L PowerShell Comparison Operators Comparison Operator Description Example -eq Determines if expression1 is equal to expression2 [PS] C:\> “Active Directory” -eq “AD” False Administering Service Delivery TA B L E 1.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Accept Script Parameters When you write a PowerShell script, there are times when you may want the user to feed some information into the script. There are two ways to handle this. The first way is to allow the user to edit the script and add their information directly. If your script was signed, however, this will break the signature. The second way is for your script to accept command parameters.
This specifies that the script will accept a string parameter called -FirstName that gets passed into the $FirstName variable inside the script. When the script is run, the user executes it with the following command: MyScript.ps1 -FirstName Brenna Use Positional Parameters When using a parameter as a positional parameter, you need to specify the parameter’s position in the parameter declaration.
CHAPTER 1 • TA B L E 1. 7 USING POWERSHELL WITH ACTIVE DIRECTORY Parameter Properties Property Name Purpose Mandatory A Boolean property that determines whether the parameter is mandatory in order for the script to run. Position An integer property that identifies the position in which a positional parameter should appear. ValueFromPipeline A Boolean property that indicates whether this parameter can accept an object that is pipelined in from another script or cmdlet.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L 33 Function DisplayMessage () { Write-Output “Hello, Ken!” } PART I In this function, the message that is displayed is hard-coded. When you call the DisplayMessage function, it will display the same message every time. You can modify this behavior by configuring a parameter that the user can pass in. There are two different ways to define parameters in functions.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Call Functions If you want to use a function that you’ve defined in your script, you have to call the function. To call the function, you simply need to type in the name of the function, similar to how you might execute a cmdlet in PowerShell.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L 35 When you write a .ps1 script, you can run that script anytime you’re in a PowerShell session. But you can also run scripts without opening PowerShell manually. The process is similar to running a batch file outside of the command prompt. You can double-click the script, and PowerShell will be automatically opened, your script will run, and then PowerShell will close. By default, when you double-click a PowerShell .
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY To change the .ps1 file association, do the following: 1. Open the Control Panel, and run the Default Programs applet. 2. When the Default Programs applet launches, select the option Associate A File Type Or Protocol With A Program. 3. Scroll down to the .ps1 fi le extension, and click it to select it. Click the Change Program button above the list of fi le types, as shown in Figure 1.12. F I G U R E 1.
U N D E R S TA N D T H E BA S I C S O F P O W E R S H E L L 37 Sometimes you’ll want to create a script and have it run repeatedly at a specified interval. Windows has a powerful Task Scheduler service that allows you to set up programs to launch in a very flexible manner. If you want to schedule a script to run at a later time or after a specified interval, you can schedule the script to run with the Task Scheduler.
CHAPTER 1 • F I G U R E 1.13 USING POWERSHELL WITH ACTIVE DIRECTORY Selecting the appropriate permissions for scheduling a script 5. Click the Actions tab, and click the New button to create a new action for this task to perform. In the Action drop-down list, choose Start A Program. In the Program/script text box, type powershell.exe. In the Add Arguments text box, type the location of the script: C:\Scripts\GetLogonStats.ps1 These options are shown in Figure 1.14. 6.
U N D E R S TA N D H O W P O W E R S H E L L A N D AC T I V E D I R E C T O RY WO R K T O G E T H E R Selecting the appropriate action for running a PowerShell script Administering Service Delivery F I G U R E 1.14 39 PART I Understand How PowerShell and Active Directory Work Together Now that you have a basic understanding of PowerShell, let’s take a closer look at how Active Directory and PowerShell work together.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Use the Active Directory Services Interface Prior to Windows Server 2008 R2, if you wanted to manage Active Directory with PowerShell, you were limited to using the Active Directory Services Interface (ADSI). ADSI is a set of Common Object Model (COM) interfaces that allow you to programmatically work with directory services such as Active Directory. ADSI is very flexible, and once you get the hang of it, it’s actually quite easy to work with.
U N D E R S TA N D H O W P O W E R S H E L L A N D AC T I V E D I R E C T O RY WO R K T O G E T H E R 41 Administering Service Delivery fact, if you pipe the user object into the Get-Member cmdlet, you can retrieve a listing of the object’s properties and methods: PS C:\> $user | Get-Member TypeName: System.DirectoryServices.DirectoryEntry Name MemberType Definition ---- ---------- ---------- ConvertDNWithBinaryToString CodeMethod static string ConvertDNWithBinaryToSt...
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY userAccountControl Property System.DirectoryServices.PropertyValu... uSNChanged Property System.DirectoryServices.PropertyValu... uSNCreated Property System.DirectoryServices.PropertyValu... whenChanged Property System.DirectoryServices.PropertyValu... whenCreated Property System.DirectoryServices.PropertyValu...
After you bind to the container, you can create the child object by calling the Create method. For this example, you’ll pass in the type of the child object being created (user) and the common name of the object (cn=Nora Shea): PS C:\> $user = $container.Create(“user”, “cn=Nora Shea”) In a manner similar to changing an object’s properties, this user is only created locally in PowerShell’s memory.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Use the Active Directory Module The Active Directory module for PowerShell is a new feature of Windows Server 2008 R2. As discussed earlier, prior to Windows Server 2008 R2, you had to use the ADSI interfaces for using PowerShell with Active Directory. Windows Server 2008 R2 provides you with several cmdlets for Active Directory administration. The Active Directory module groups these cmdlets together into a package.
As mentioned earlier, the AD PowerShell module requires either a Windows Server 2008 R2 domain controller or a Windows Server 2003/2008 domain controller running ADMG. If there are none available, you’ll receive an error when attempting to import the module stating that a server with ADWS can’t be found. After the module loads successfully, you can begin using the Active Directory cmdlets.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY Get-ADRootDSE Get-ADServiceAccount Get-ADUser Remove-ADComputer Remove-ADComputerServiceAccount Remove-ADDomainControllerPasswordReplicationPolicy Remove-ADFineGrainedPasswordPolicy Remove-ADFineGrainedPasswordPolicySubject Remove-ADGroup Remove-ADGroupMember Remove-ADObject Remove-ADOrganizationalUnit Remove-ADPrincipalGroupMembership Remove-ADServiceAccount Remove-ADUser Rename-ADObject Reset-ADServiceAccountPassword Restore-ADObject Search-ADAcco
U N D E R S TA N D H O W P O W E R S H E L L A N D AC T I V E D I R E C T O RY WO R K T O G E T H E R 47 In addition to providing the Active Directory cmdlets, the Active Directory module for PowerShell also provides a new drive called the AD drive. With the AD drive, you can navigate Active Directory in a manner similar to the way you would navigate the file system on your hard drive.
CHAPTER 1 • USING POWERSHELL WITH Infrastructure ACTIVE DIRECTORY infrastructureUpdate CN=Infrastructure,DC=contoso, DC=com Jenny Smith contact CN=Jenny Smith,DC=contoso, DC=com Jim Johnson user CN=Jim Johnson,DC=contoso, Joe User contact CN=Joe User,DC=contoso,DC=com LostAndFound lostAndFound CN=LostAndFound,DC=contoso, DC=com DC=com Managed Service A...
U N D E R S TA N D H O W P O W E R S H E L L A N D AC T I V E D I R E C T O RY WO R K T O G E T H E R 49 WMI Basics WMI provides an object-oriented way to manage Windows. WMI uses the concept of classes, which define different types of objects that WMI can interact with. Similar to how .NET classes work, WMI provides methods (pieces of executable code) and properties. Windows provides a series of classes out of the box for interacting with core Windows components.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY This example connects to the root\cimv2 namespace and uses the class StdRegProv, which provides access to the system’s registry. In addition to using the WMI provider, PowerShell provides a series of cmdlets you can use to interact with WMI. You can view these cmdlets by running the following command: PS C:\> get-command -Noun *wmi* CommandType Name Definition ----------- ---- ---------- Cmdlet Get-WmiObject Get-WmiObject [-Class] ...
may encounter is that if there is a firewall between your domain controller and the computer from which you’re running the Active Directory PowerShell module, the module may not be able to connect to ADWS. To fix this, you should ensure that you allow traffic on TCP port 9389 to communicate with the domain controller.
CHAPTER 1 • F I G U R E 1.15 USING POWERSHELL WITH ACTIVE DIRECTORY ADWS Running on a Windows 2003 domain controller Use Windows 7 or Windows Server 2008 R2 for Administration When you promote a Windows Server 2008 R2 server to a domain controller, the Active Directory module is installed by default. Therefore, you can use the Active Directory PowerShell module on the domain controller without additional configuration.
Windows 7 doesn’t include the RSAT feature by default. Therefore, you’ll need to download and install these tools before you can enable the Active Directory module on Windows 7. You can download RSAT from Microsoft’s website at the following URL: www.microsoft.com/downloads/en/details.aspx?FamilyID= 7d2f6ad7-656b-4313-a005-4e344e43997d. After you install RSAT, you can use the following steps to install the Active Directory module in Windows 7: 1. Click the Start menu, and select Control Panel. 2.
CHAPTER 1 • USING POWERSHELL WITH ACTIVE DIRECTORY 3. Export the AD cmdlets from the remote session into a local copy of the module. The following example references all the cmdlets that contain -AD in the name: Export-PSSession -Session $session -CommandName *-AD* i -OutputModule LocalADModule -AllowClobber 4.