Use Active Directory Cmdlets with PowerShell to Find Users

Use Active Directory Cmdlets with PowerShell to Find Users

  • Comments 16
  • Likes

Summary: Learn about the Microsoft Active Directory Windows PowerShell cmdlets, and use them to find active and disabled users.

 

Hey, Scripting Guy! QuestionHey, Scripting Guy! I am wondering what the best way is to use Windows PowerShell to work with Active Directory. I have seen all different methods talked about on the Internet, and many of them require downloading and installing third-party software. Can you possibly discuss how to work with Active Directory and Windows PowerShell, and maybe even discuss the pros and the cons of each approach? It would help us at work as we try to set our strategic direction.

—TU

 

Hey, Scripting Guy! AnswerHello TU,

Microsoft Scripting Guy Ed Wilson here. This week, the Scripting Wife and I are lying around on the beach in Kauai. Kauai, Hawaii, is a wonderful island that is like a garden paradise, with cobalt blue water that is so clear you can often see the ocean bottom while standing on the deck of a boat. Here is a picture of a turtle I took on my last dive trip to the island.

Photo Ed took of a sea turtle in Kauai, Hawaii

My first choice for working with Active Directory from within Windows PowrShell, is to use the Active Directory cmdlets that are supplied with Windows Server 2008 R2. There are actually a couple of ways to use these cmdlets. One way is to install the Remote Server Admin Tools (RSAT) for Windows Server 2008 R2 onto your Windows 7 computer. A link to these tools is on the Script Center Downloads page. There is a package for each version of Windows 7 (x86 and x64), as well as a build that is service-pack specific. Unfortunately, the installation cannot run from a server share, so the package must be copied locally. After it is copied, the installation proceeds without interruption. But that does not give you access to the actual tools; it simply places the files on your computer.

The first thing to do:

  1. Click the Start button, and then, on the Start menu, click Control Panel.
  2. Click Programs and Features and then click Turn Windows Features on or off.  
  3. Click Windows Features to see if the RSAT tools are installed on the computer.

As shown in the following figure, on a default installation of Windows 7, the RSAT tools are not installed.

Image showing RSAT not installed

When I attempt to install the RSAT tools, I am prompted for administrative credentials, as shown in the following figure. A normal, non-elevated user cannot install the tool set.

Image of prompt for administrative credentials

I provide credentials. Everything should be groovy. Wait, not yet. I am now prompted to install update KB958830. What in the world is that? Well, it is the technical name for RSAT. Click Yes, accept the license agreement, and there will be no more prompts.

Image of prompt to install RSAT

After the tools are installed, follow steps 1–3 above, find the Remote Server Administration Tools section, and choose the tools you want to make available. Unfortunately, this requires quite a bit of clicking because there is no way (that I know of) to click once and make all the tools available. The one tool you definitely do not want to inadvertently miss is under AD DS and AD LDS tools – Active Directory Module for Windows PowerShell. This critical check box is shown in the following figure.

Image of critical check box you must select

After the RSAT tools have been installed and configured, the next step is to import the activedirectory module. To do this, use the Import-Module cmdlet, as shown here:

Import-Module activedirectory

On my system, at times this command generates this warning message: “WARNING: Error initializing default drive: 'Unable to find a default server with Active Directory Web Services running.'”

The warning is generated because I have several domain controllers, and not all of them have the Active Directory Management Gateway Service installed. Depending on which domain controller authenticated my workstation, the warning appears. The solution is to install the Active Directory Management Gateway Service on all of the non-Windows Server 2008 R2 domain controllers. The other solution is to ignore the warning and specify the server parameter each time when using one of the cmdlets (but that will mean the PSDrive will be unavailable).

More than six years ago, a different Microsoft Scripting Guy wrote an article called How Can I Get a List of All the Disabled User Account Accounts in Active Directory? it was an immediate classic that continues to generate discussion even today. The VBScript to retrieve disabled user accounts is cryptic at best and downright confusing at worst. It is not horribly long, as far as VBScripts go; it checks in at 16 lines of code. It also uses COM-based ADO, which as far as VBScripters go is part and parcel of the game. No, it is not the VBScript or the ADO that is confusing; it is the UserAccountControl bitmask attributes that are the game changer.

Luckily, for those of us who are using Windows PowerShell and the Microsoft Active Directory cmdlets, it takes a single line of code to retrieve the disabled users in the domain. The command is shown here (keep in mind that before running this command, I had imported the activedirectory module into the current Windows PowerShell host):

Get-ADUser -Filter 'enabled -eq $false' -Server dc3

Not only is the command a single line of code, but also it is a single line of readable code. I really do not need to explain the command at all because the code is clearly understandable. I get users from Active Directory, and I use a filter that looks for the enabled property set to false. I also specify that I want to query a server named dc3 (the name of one of the domain controllers on my network). The command and the associated output are shown in the following figure.

Image of command and associated output

If I want to work with a specific user, I can use the identity parameter. The identity parameter accepts several things: DistinguishedName, SID, GUID, and SamAccountName. Probably, the easiest one to use is the SamAccountName. This command and associated output are shown here.

PS C:\Users\ed.IAMMRED>    Get-ADUser -Server dc3 -Identity teresa

 

DistinguishedName : CN=Teresa Wilson,OU=Charlotte,DC=iammred,DC=net

Enabled           : True

GivenName         : Teresa

Name              : Teresa Wilson

ObjectClass       : user

ObjectGUID        : 75f12010-b952-4d16-9b22-3ada7d26eed8

SamAccountName    : Teresa

SID               : S-1-5-21-1457956834-3844189528-3541350385-1104

Surname           : Wilson

UserPrincipalName : Teresa@iammred.net

 

To use the DistinguishedName value for the identity parameter, I need to supply it inside a pair of single or double quotation marks. This command and associated output are shown here.

PS C:\Users\ed.IAMMRED>    Get-ADUser -Server dc3 -Identity 'CN=Teresa Wilson,OU=Charlotte,DC=iammred,DC=net'

 

DistinguishedName : CN=Teresa Wilson,OU=Charlotte,DC=iammred,DC=net

Enabled           : True

GivenName         : Teresa

Name              : Teresa Wilson

ObjectClass       : user

ObjectGUID        : 75f12010-b952-4d16-9b22-3ada7d26eed8

SamAccountName    : Teresa

SID               : S-1-5-21-1457956834-3844189528-3541350385-1104

Surname           : Wilson

UserPrincipalName : Teresa@iammred.net

 

It is not necessary to use quotation marks when using the SID for the value of the identity parameter. This command and associated output are shown here.

PS C:\Users\ed.IAMMRED>    Get-ADUser -Server dc3 -Identity S-1-5-21-1457956834-3844189528-3541350385-1104

  

DistinguishedName : CN=Teresa Wilson,OU=Charlotte,DC=iammred,DC=net

Enabled           : True

GivenName         : Teresa

Name              : Teresa Wilson

ObjectClass       : user

ObjectGUID        : 75f12010-b952-4d16-9b22-3ada7d26eed8

SamAccountName    : Teresa

SID               : S-1-5-21-1457956834-3844189528-3541350385-1104

Surname           : Wilson

UserPrincipalName : Teresa@iammred.net

 

Once again, I can also use the ObjectGUID for the identity parameter value. It does not require quotation marks either. This command and associated output are shown here.

PS C:\Users\ed.IAMMRED>    Get-ADUser -Server dc3 -Identity 75f12010-b952-4d16-9b22-3ada7d26eed8

 

DistinguishedName : CN=Teresa Wilson,OU=Charlotte,DC=iammred,DC=net

Enabled           : True

GivenName         : Teresa

Name              : Teresa Wilson

ObjectClass       : user

ObjectGUID        : 75f12010-b952-4d16-9b22-3ada7d26eed8

SamAccountName    : Teresa

SID               : S-1-5-21-1457956834-3844189528-3541350385-1104

Surname           : Wilson

UserPrincipalName : Teresa@iammred.net

 

TU, that is all there is to using Windows PowerShell with Active Directory. Active Directory Week will continue tomorrow.

 

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

 

 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Nice article, can you show some examples on how to use these tools in a domain environment where users exist in a domain that has a one-way external trust to the domain where the scripts are running? Also, FSP's, they are the devil, I've not had a chance to poke through all these tools yet, but can these tools help with querying and adding FSPs to a local domain?

    Thanks!

  • The tools are very powerful and can be used across domains. If you look at the -- Get-Help Get-ADUser -Full -- you can specify Server and Credential meaning that you should be able to connect to anything. The trick is to have the ADWS installed which come standard in Windows 2008 R2. If you have only 2003 servers in a Domain, you will need to install the ADWS to use the ActiveDirectory module.

  • This will be a nice article to reference for Powershell beginners; might be a nice starting point for some co-workers.  

    Are you planning an article to show how to create new users in AD with splatting?  That would something a large majority of IT pros would be able to use almost immediately.

  • Hi Ed,

    that's fun!

    Jumpstart into AD administration with Powershell and the ActiveDirectory module is something that sounds very interesting!

    Klaus.

  • @Jeffrey thanks. Yes, the tools do work cross domain

    @aemiller you are right

    @Rich I have had numerous articles on splatting, written by James B. as well as myself. Splatting is a nice technique, and could be profitably used here.

    @klaus thanks

  • I'm looking for a script to find out the disabled user account from AD and remove their mailbox from exchange server. This should exclude room mailbox and shared mailbox which are disabled by default.

    Any help would be appreciated

    Thank you

  • Shafeeq,

    My first suggestion would be to separate standard, room, and shared mailbox user accounts into separate OUs in AD for ease of administration. This will make your life much easier. Is there a business reason you're keeping disabled accounts around? I find they just clutter AD. With that in mind, I have two scenarios for you:

    Removing disabled users from AD:

    Import-Module ActiveDirectory

    Get-ADUser -Filter { Enabled -eq $false } -SearchScope Subtree -SearchBase "OU=Standard Users,DC=yourdomain,DC=com" | Remove-ADUser -Confirm:$false

    Removing disabled users' mailboxes from Exchange:

    Import-Module ActiveDirectory

    Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin #if you have Exchange 2007 Management Tools installed

    Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 #if you have Exchange 2010 Management Tools installed

    Get-ADUser -Filter { Enabled -eq $false } -SearchScope Subtree -SearchBase "OU=Standard Users,DC=yourdomain,DC=com" | Remove-Mailbox -Identity $_.SamAccountName -Confirm:$false

    Of course, in production you'll want to add additional code for logging as well as any checks and balances and exceptions you may need to handle.

    On a final note, I don't often use the ActiveDirectory module when working with Exchange because I don't install AD tools on my Exchange servers, and quite often, I'm looking for some esoteric ADSI attribute. If that's the case with you, I'd suggest familiarizing yourself with the C# class, System.DirectoryServices.DirectoryEntry, and the PowerShell DataType alias, [adsi].

    -Jeremy

  • Oops, I typed too fast. That last command should be Disable-Mailbox, not Remove-Mailbox!

    Get-ADUser -Filter { Enabled -eq $false } -SearchScope Subtree -SearchBase "OU=Standard Users,DC=yourdomain,DC=com" | Disable-Mailbox -Identity $_.SamAccountName -Confirm:$false

  • How do you get the 'import-module ActiveDirectory' to load in the x64 powershell? All I get when I attempt to import it is:

    import-module ActiveDirectory

    Import-Module : Could not load file or assembly 'Microsoft.ActiveDirectory.Management' or one of its dependencies. An a

    rgument was out of its legal range. (Exception from HRESULT: 0x80131502)

    At line:1 char:14

    + import-module <<<<  ActiveDirectory

       + CategoryInfo          : InvalidOperation: (:) [Import-Module], FileLoadException

       + FullyQualifiedErrorId : FormatXmlUpateException,Microsoft.PowerShell.Commands.ImportModuleCommand

    When I do this after opening PowerShell x86 I don't get the error.

  • Nice article.

  • Save this script as Set-InheritablePermissions.ps1

    ## Script Name Set-InheritablePermissions.ps1

    ## sets the "Allow inheritable permissions from parent to propagate to this

    ##object"check box

    # Contains DN of users

    #

    #$users = Get-Content C:\C:\Navdeep_DoNotDelete\variables\users.txt

    Get-ADgroup -LDAPFilter “(admincount=1)” | select name

    $users = Get-ADuser -LDAPFilter “(admincount=1)”

    ##Get-QADUser -SizeLimit 0 | Select-Object Name,@{n=’IncludeInheritablePermissions’;e={!$_.DirectoryEntry.PSBase.ObjectSecurity.AreAccessRulesProtected}} | Where {!$_.IncludeInheritablePermissions}

    ForEach($user in $users)

    {

    # Binding the users to DS

    $ou = [ADSI]("LDAP://" + $user)

    $sec = $ou.psbase.objectSecurity

    if ($sec.get_AreAccessRulesProtected())

      {

      $isProtected = $false ## allows inheritance

      $preserveInheritance = $true ## preserver inhreited rules

      $sec.SetAccessRuleProtection($isProtected, $preserveInheritance)

      $ou.psbase.commitchanges()

      Write-Host "$user is now inherting permissions";

      }

    else

      {

       Write-Host "$User Inheritable Permission already set"

      }

      }

  • Is there a way to also filter who has been disabled within the last 24 hours?

  • Hi,

    I am trying to update the Employee information on Active Directory (which is on version 2008 R2). Based on my reasearch on ADWS, I understood that there are some web services available in 2008 R2 version of ADWS that are publicly accessible. But I do not have any clear documentation to confirm that. We are trying to access one of the Account management webservice via http or soap

    net.tcp://<host-server>:9389/ActiveDirectoryWebServices/Windows/AccountManagement

    via a browser after connecting to the host network via VPN. But it does not work. What I feel is that this web service should be hosted on a webserver like IIS for it to be publicly accessible via Internet.  Like the one below instead of net.tcp

    http://<host-server>:9389/ActiveDirectoryWebServices/Windows/AccountManagement

    But the client side hosting this service says that it is hosted on IIS. Could anyone please guide me if anything is missing here ?

    Thanks a bunch!

  • @Microsoft Active Directory Webservices - R2 2008 Issue

    Yes this is an issue with Microsdt.  They tend to use IIS for most things.  Perhaps a support call would get you some relief.

    Basically RSAT is a method for bonding WS2003 and WS2008 AD services and allows us to join WS2003 Domains to WS2008 domains.  It is not realy a user specific public access solution.  That is to say that you cannot browse AD from the Internet with RSAT or ADWS.  This was never the intention and will not likely ever be implemented.

  • thanks