Making Powershell with Active Directory More User Friendly

I wanted an easier way to run powershell against AD OUs without having to worry about the some of the long strings we have to write for example

OU=Ireland, OU=Europe, OU=Earth, DC=Test, DC=local

No One really wants to type something like that out every time the just want to run some simple powershell AD queries.

So I came up with a short little script that you can throw into existing scripts to make your life more enjoyable.

param([string]$local=$(Read-Host "What OU Path?"))
$path="DC=DTS,DC=com" # Changeme To your domain!!!

while($i -le ($location.length-1))

What this does is transform what we would normally think of in terms of a path location and transforms it into what most of the AD cmdlets in powershell are looking for. It seperates the location OU into an array with the split method the adds it to the $path variable which could then be used as a -searchbase…

Here is an example

Picture from "Implementing Active Directory Delegation of Administration"

First I should note that when using this you should change line 2 to match the domain you want to run this against.

So in this example, looking at the picture, lets say you want to run your script again the FinanceUsers OU. Easy!!!

When prompted define $local to be employees/departments/Financeusers

Which for most of us being Windows based makes a lot more sense than OU=Financeusers,OU=Departments,OU=Employees,DC=dts,DC=com , not to mention it’s a LOT quicker to type.

This obviously shines when your script’s goal is to do a get-aduser  or get-adcomputer against a specific OU.

What would you use this for???

4 Responses to Making Powershell with Active Directory More User Friendly

  1. Well this looked like fun so I had to try a few things. Here are some other ways you might work this, especially if you have the Microsoft AD provider loaded.


    #split array on either / or
    $a=$local -split “[/|\]”

    #reverse the array and prepend OU=
    $b=$a[($a.count-1)..0] | foreach {“OU=$_”}

    #change to the AD PSdrive
    CD AD:

    #join everything together. The second join takes the array of strings in $b and
    #concatenates to a comma separated string
    $dn=join-path $dc ($b -join “,”)

    #the provider will magically make this work.

    If you don’t use the provider, $dn will have a slash, but that is easily replaced.

Leave a Reply