PowerShell for Active Directory Examples

Andrei published on PowerGUI.org a bunch of how-to’s to Active Directory management with PowerShell:

In these posts Andrei shares some of his tips and tricks for using free Active Directory cmdlets to manage your AD environment.

Among the scenarios he covers are:

  • Enumerating users, groups and other objects
    • List all users in my domain
    • List all users in a specific OU
    • Get help on Get-QADUser parameters
    • Get specific user properties
    • List first-level organizational units in your domain
    • List all users in my domain with their display name and city
    • Find all users in my domain that has City attribute starts with ‘ny’
  • Updating user properties
    • Set description for a specific user account:
    • Set city to Liverpool for all user accounts in the Demo OU
  • User creation
    • Create user accounts
  • Group operations
    • Create a new group
    • Add all users with a specific description to a group
    • List group members, display names and descriptions
  • Bulk creation
    • Export useraccounts to a CSV file
    • Import useraccounts from a CSV file
    • Import useraccounts from CSV file and add them to a specific group
  • Statistics:
    • Count users, groups, OUs
    • Count departments
    • Get statistics for departments, locations, etc.
    • Count mailboxes per each mailbox store (will work against Exchange 2000 and Exchange 2003)

Note that all of them are one-liners! Managing Active Directory from command line has never been so easy.

Technorati Tags: , , , ,

About these ads

30 Responses to “PowerShell for Active Directory Examples”


  1. 1 Jon Biddell October 22, 2007 at 2:55 am

    Just wondering if it is possible to pull from AD a list of all users and, by user, a list of what AD objects they have access to ?

    As part of our PCI compliance audit I need to list these for the auditors.

    Would PowerShell be able to do this ? What I need is something like;

    user object rights
    tsjbil \\server\common rwx

    Jon

  2. 2 dmitrysotnikov October 22, 2007 at 10:56 am

    Jon,

    This is a great question. Currently AD permissions are not a part of the AD cmdlets set, so you would need to use .NET for tasks like that (or use a commercial reporting tool such as Quest Reporter but my understanding is that you would like to solve the task with a script instead.)

    We are considering adding this functionality in one of the future cmdlet releases but it is hard to provide any timeline at this point.

    Dmitry

  3. 3 dmitrysotnikov October 22, 2007 at 11:01 am

    By the way, do you need direct rights only or the ones obtained through group membership as well?

  4. 4 Igor January 9, 2008 at 8:54 am

    Добрый день, Дмитрий. Подскажите, пожалуйста, как можно изменить свойство msExchHideFromAddressLists (поставить true or false)

  5. 5 Igor January 9, 2008 at 12:03 pm

    P.S. Мы используем Exchange 2003.

  6. 6 dmitrysotnikov January 9, 2008 at 12:50 pm

    Игорь, используйте ключ -ObjectAttributes. Например:

    Set-QADUser dsotniko -oa @{‘msExchHideFromAddressLists’=$true}

    или

    Get-QADUser a* | Set-QADUser -oa @{‘msExchHideFromAddressLists’=$true}

  7. 7 Igor January 9, 2008 at 2:51 pm

    Большое спасибо за помощь!

  8. 8 Cyrill March 21, 2008 at 10:26 am

    Привет,

    спасибо за шикарный доклад на heroes2008 =) один из лучших, на мой взгляд.

  9. 9 Andrew Wood April 18, 2008 at 10:18 am

    Great Example and have proved most useful for quickly setting up test environments. I am however having a problem with bulk creating nested OU’s.

    If I create an OU in the root of my domain using New-QADObject e.g

    New-QADObject -ParentContainer ‘dc=datalex,dc=com’ -Type ‘organizationalUnit’ -NamingProperty ‘ou’ -name ‘South Africa’

    then try and then immediately try and create a new OU within it e.g.

    New-QADObject -ParentContainer ‘ou=South Africa,dc=datalex,dc=com’ -Type ‘organizationalUnit’ -NamingProperty ‘ou’ -name ‘Users’

    I get an error

    New-QADObject : Cannot resolve DN for the given identity: ‘ou=South Africa,dc=d
    atalex,dc=com’
    At line:1 char:14
    + New-QADObject <<<< -ParentContainer ‘ou=South Africa,dc=datalex,dc=com’ -Typ
    e ‘organizationalUnit’ -NamingProperty ‘ou’ -name ‘Users’

    However if i do a Get-QADObject -type ‘organizationalUnit’ -name ‘South Africa’ it return the object no problem.

    If I wait a few seconds and try to create the sub OU again it works fine but I need to do this in a script to quickly create a bunch of nested OU’s.
    Is this a bug in the New-QADObject? Are there any ways I can work around it ?

    Thanks

    Andrew Wood

  10. 10 Andrew Wood April 18, 2008 at 1:56 pm

    OK Well I decided that the most efficent way to continue would be to just keep trying until it worked by trapping the error and looping until no error was raised.

    New-QADObject -ParentContainer ‘dc=datalex,dc=com’ -Type ‘organizationalUnit’ -NamingProperty ‘ou’ -name ‘South Africa’
    Do { sleep 1; New-QADObject -ParentContainer “ou=South Africa,dc=datalex,dc=com” -Type ‘organizationalUnit’ -NamingProperty ‘ou’ -name ‘Users’ -ErrorAction SilentlyContinue -ErrorVariable test ; trap {Continue} }
    Until ($test.Count -lt 1)

    You could make this more robust by only trapping the DN not found error in case there are other reasons an error is thrown. In fact if your going to do this in a production environment I’d say it was essential.

  11. 11 dmitrysotnikov April 18, 2008 at 7:11 pm

    Andrew,

    That’s interesting. Could you post questions like that to the forums at PowerGUI.org? A lot of really smart guys including the dev team are there to help.

    Dmitry

  12. 12 ben June 25, 2008 at 7:59 am

    Hi,

    I want to do this script :

    Search atttribu user departement to AD and :

    if objUser.Get(“departement”) = “%variable%” then
    add group “%variable%”
    group=”cn=%variable%”
    ouGroups=”ou=NoIAM,ou=%variable%,”
    ouMoveUser=”ou=%variable%”

    Have you an idea ?.

    Thank.

  13. 13 dmitrysotnikov June 25, 2008 at 6:10 pm

    Ben, this code of yours is definitely not PowerShell. Come join our side and we’ll be here to help. ;)

    PowerGUI.org has a pretty good AD Management forum (but again for PowerShell only)

  14. 14 Daniel Anderson October 30, 2008 at 12:04 am

    Is there a way to import Active Directory Users with their associated passwords?

  15. 16 Dmitry Sotnikov October 30, 2008 at 6:08 am

    If you want to import passwords for existing accounts (not create new accounts), then use this link instead: http://dmitrysotnikov.wordpress.com/2008/10/03/update-active-directory-user-accounts-from-csv-file/

  16. 17 Richard November 24, 2008 at 2:12 pm

    Hi Dmitry,

    When I use Set-QADObjectSecurity -LockInheritance on an address list and then Edit the Address List security Advanced view via ADSIEdit/Object properties/Security, I get a window stating that ‘the permissions are incorrectly ordered… Click on Reorder…’. This creates a problem when I try to script adding and removing permissions with Add- and Remove-ADPermission. Is there any simple way to reorder ACES in DACL with PowerShell as I suspect this is the problem? Thanks for your help!

    Richard

  17. 18 Dmitry Sotnikov November 24, 2008 at 2:16 pm

    Richard,

    This sounds like a fairly nasty problem and I don’t have the answer right away.

    Could you post this to the PowerShell and AD forum at http://powergui.org/forum.jspa?forumID=173 ? The AD cmdlets team is watching this and should be able to help you find the solution.

    Dmitry

  18. 19 Moe December 3, 2008 at 11:12 pm

    Dmitry,

    Hello and thank you for your site.

    I have a PS script to identify all computer accounts which have not been logged onto for a set number of days. The script queries the lastlogon time for each computer account on all discoverable domain controllers within the domain.

    Currently, I have the following line:
    $DCs = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().FindAllDiscoverableDomainControllers()

    the above works, but for testing purposes, I only want to query 1 or 2 domain controllers.

    I have tried changing the above line to:
    $DCs = (‘srv001.mycompany.com’,’srv002.mycompany.com’)

    But further down the code when $DC.name is referenced, the value for neither DC is carried over and an error results.

    Thank you in advance for any assistance you can provide.

  19. 20 Dmitry Sotnikov December 4, 2008 at 6:27 am

    Moe,

    This is because your new line creates an array of strings – not DC objects.

    You could for example try modifying this to:

    $DCs = (‘srv001.mycompany.com’,’srv002.mycompany.com’ | Get-QADComputer )

    If you cannot get this working, try asking the experts at the PowerShell AD forum: http://powergui.org/forum.jspa?forumID=173 – these guys are way smarter than me. ;)

    Dmitry

  20. 21 Moe December 10, 2008 at 8:10 pm

    Dmitry,

    Thanks. That did work, although a little slower than I anticipated but never the less, it did work.

    I have also posted this on the PowerGui.org forum as you recommended. Thanks again for your site.

  21. 22 Igor February 24, 2009 at 3:21 pm

    Hallo Dmitry!
    How can I get members of AD group (by Get-QADGroupMember..) without members of groups that included in it?
    Thank you!
    Заранее спасибо за ответ.

  22. 23 Igor February 24, 2009 at 3:27 pm

    I mean I want to get user members of AD group without members of groups that also are included in group that I work with.

  23. 24 Dmitry Sotnikov February 24, 2009 at 3:29 pm

    Igor,

    This is actually the default behavior:

    Get-QADGroupMember MyGroup

    will return only first level members.

    Get-QADGroupMember MyGroup -Indirect

    will return members of nested groups as well.

    Dmitry

  24. 25 Marko Cesar October 19, 2009 at 2:15 pm

    Can someone help me to pre-create large number of computer objects from csv and assign security group which can join those computers to domain.

    I can create them, but cannot assign proper rights.

    I tried to manualy assign rights to computer object SOURCE and then
    “get-qadpermission SOURCE | add-qadpermission TARGET”, but was not able to join computer SOURCE to domain with member of group.

    Thanks!

  25. 26 Afterpopulation December 4, 2009 at 8:09 pm

    Nothing Alone,local there straight aye commit guide revenue certain active through different couple establishment success thing skin her evening provide stuff below soft female bill present limited edge wave movement means committee treatment agreement solution official neither too mechanism fashion observe pay to set lady principle session few hole train award think cost against almost fruit flower read to bone son gather paint establishment attract domestic reflect significance usual plan concern off accident sequence separate effort pressure copy foreign expression reaction notice reform favour county party wood total lunch throughout news

  26. 27 mcdonnj February 1, 2010 at 1:48 pm

    Hi there

    I have written a small script to parse a list of machine names and bulk add (stage) computer accounts in advance of a Disaster Recovery test. The machine accounts are created no problem as I have run the Quest AD poweshell program under my domain admin context, the problem is that when a normal desktop admin tries to join the machines to the domain they get an access denied error! If I then use the domain admin account I can join the machines to the domain without issue, a normal user should be able to join an existing machine account to the domain. Any ideas? My script is below, I have chnaged the ldap path for the sake of privacy.

    get-content c:\desktop.txt |
    Foreach-object {
    $desktop = $_
    Write-Host “Adding Desktop: $desktop to AD”
    New-QADComputer -ParentContainer ‘OU=test,OU=emea,OU=desktops,DC=Mydomain,DC=MyForest,DC=com’ -Description ‘Desktop’

    -Name $_
    }

    Any help would be appreciated

    mcdonnj

    • 28 Dmitry Sotnikov February 2, 2010 at 2:53 am

      mcdonnj,

      Looks like indeed the account lacks permissions for creating computer accounts in AD. I would recommend that you post the question to the “Active Directory and PowerShell” forum at http://powergui.org – there are quite a few really smart AD PowerShell guys – including the QAD cmdlets team – who should be able to help you out.

      Dmitry


  1. 1 AD provider vs. AD cmdlets « Dmitry’s PowerBlog Trackback on April 26, 2007 at 8:50 pm
  2. 2 Subscribe Confirmed Subscription to Posts on Dmitry’s PowerBlog: PowerShell and beyond « Wag the Real Trackback on September 17, 2011 at 12:48 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




My Recent Tweets

Legal

The posts on this blog are provided “as is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer - WSO2 or anyone else for that matter. All trademarks acknowledged.

© 2007-2014 Dmitry Sotnikov

April 2007
M T W T F S S
« Mar   May »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Follow

Get every new post delivered to your Inbox.

Join 2,329 other followers

%d bloggers like this: