Today, I am going to show how we can leverage the power of Powershell V2 and Active Directory Module, and easily write powerful, professional cmdlets (with help message, positional parameters, default prompting, error handling etc.) for AD.

Couple of weeks ago, one of my colleagues (Alexander Lash) introduced me to a cool feature in Powershell V2 called Advanced Functions, using which one can write full-blown cmdlets within a module natively in Powershell! I thought of experimenting with this feature a little bit and build some cmdlets that would extend the current functionality of AD cmdlets. The outcome of my experimentation is a new module called ActiveDirectoryExtension in which I and some of my team members are planning to add utility functions/cmdlets built using Active Directory Module cmdlets.

The first set of the cmdlets that I am publishing today is an extension of Get-ADUser, Get-ADGroup cmdlets that would support NT4 style account names (domain\username) and UPNs (UserPrincipalName ex: username@domain.com) as identity.

Here is some sample usage using my new set of cmdlets. I have prefixed all the nouns with “XAD” meaning eXtending AD.

Loading ActiveDirectoryExtension module

Run ActiveDirectoryExtensions.ps1 in a Powershell Console and import ActiveDirectoryExtensions module. Scroll below for complete script and download instructions.

PS C:\> C:\ActiveDirectoryExtension.ps1
PS C:\> import-module ActiveDirectory

Tips: Copy the above commands into your $PROFILE file, so that both ActiveDirectory and ActiveDirectoryExtension will always be loaded when you open a new Powershell console.

Sample commands using the new extension cmdlets

PS C:\> Get-XADUser administrator
PS C:\> Get-XADUser fabrikam\administrator       ## NT4 Style name. Should work for cross forest and cross domain scenarios too.
PS C:\> Get-XDAUser administrator@fabrikam.com   ## UPN. NOTE: UserPrincipalName must be set on the account for this to work.
                                                 ## Should work for cross domain scenarios.

PS C:\> Get-XADComputer myMemberServer *         ## Fetches all the attributes set on the computer object with identity myMemberServer.
PS C:\> Get-XADComputer myMemberServer *  | Out-SortADProperties     ## Sorts and displays all the properties found in the object as string.

PS C:\> Get-PossibleLdapAttributes user        ## Prints out all the Ldap Attributes that can be set on a user object
PS C:\> Get-PossibleLdapAttributes computer    ## Prints out all the Ldap Attributes that can be set on a computer object
PS C:\> Get-PossibleLdapAttributes group       ## Prints out all the Ldap Attributes that can be set on a group object
PS C:\> Get-PossibleLdapAttributes msDS-ManagedServiceAccount  ## Prints out all the Ldap Attributes that can be set on a service account object

Script

Here is the complete script:

NOTE: This script is just for proof-of-concept and is not intended to be production quality.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#
# URL: http://blogs.msdn.com/adpowershell
# NOTE: This script is just for proof-of-concept and is not intended to be production quality.
#

new-module -name ActiveDirectoryExtension -scriptblock {

#
# Description: This function sorts all the properties found in a ADEntity and
# writes it to the console as string.
# Tested using: Windows 2008 R2 Beta.
#
function Out-SortADProperties() {     
   foreach ($msADE in $input) {
        $msADEProps = $msADE.PropertyNames | sort
        if ($msADEProps -ne $null) {
            foreach ($msADEProp in $msADEProps) {
                $msADEProp.ToString().PadRight(23) + ": " + $msADE[$msADEProp]
            }
        }
    }
}



#
# Description: This function lists all the Ldap attributes that can be set on
# the specified objectClass.
# Tested using: Windows 2008 R2 Beta.
#
function Get-PossibleLdapAttributes() {
    Param ([Parameter(Mandatory=$true, Position=0)] [String] $ObjectClass)
    $rootDSE = Get-ADRootDSE
    $schemaObject = get-adobject  -filter { ldapdisplayname -like $ObjectClass } -Properties mayContain, SystemMayContain, SubClassOf -searchbase  $rootDSE.SchemaNamingContext
    $schemaObject.MayContain
    $schemaObject.SystemMayContain
    if ($ObjectClass -ne "top" -and $schemaObject.SubClassOf -ne "" -and $schemaObject.SubClassOf -ne $null) {
        Get-PossibleLdapAttributes $schemaObject.SubClassOf
    }
}


#
# Description: The following functions are an extension (or wrapper) over Get-ADUser,
# Get-ADGroup, Get-ADComputer and Get-ADServiceAccount cmdlets.
# In addition to all the accepted form of identities for Get-ADUser, this function
# supports NT4 style names (ex: fabrikam\administrator) and UserPrincipalName - UPN (ex:
# administrator@fabrikam.com)
# NOTE: NT4 style names would work for cross-forest and cross-domain scenarios.
# UPN names would work only for cross-domain scenarios.
# Tested using: Windows 2008 R2 Beta.
#
function Get-XADUser() {
    Param (
        [Parameter(Mandatory=$true, 
                   Position=0,
                   ValueFromPipeline=$true,
                   HelpMessage="Identity of the User. NOTE: NT4 Style names such as: fabrikam\administrator and UPNs such as: administrator@fabrikam.com is acceptable"
                   )]
        [Object] $Identity,
        [Parameter(Mandatory=$false, 
                   Position=1,
                   HelpMessage="List of properties to fetch"
                   )]
        [Object] $Properties
    )
    Get-XADPrincipal -Identity $Identity -ObjectType "ADUser" -Properties $Properties
}

function Get-XADGroup() {
    Param (
        [Parameter(Mandatory=$true, 
                   Position=0,
                   ValueFromPipeline=$true,
                   HelpMessage="Identity of the Group. NOTE: NT4 Style names such as: fabrikam\administrators"
                   )]
        [Object] $Identity,
        [Parameter(Mandatory=$false, 
                   Position=1,
                   HelpMessage="List of properties to fetch"
                   )]
        [Object] $Properties
    )
    Get-XADPrincipal -Identity $Identity -ObjectType "ADGroup" -Properties $Properties
}

function Get-XADComputer() {
    Param (
        [Parameter(Mandatory=$true, 
                   Position=0,
                   ValueFromPipeline=$true,
                   HelpMessage="Identity of the Computer. NOTE: NT4 Style names such as: fabrikam\mymachine"
                   )]
        [Object] $Identity,
        [Parameter(Mandatory=$false, 
                   Position=1,
                   HelpMessage="List of properties to fetch"
                   )]
        [Object] $Properties
    )
    Get-XADPrincipal -Identity $Identity -ObjectType "ADComputer" -Properties $Properties
}

function Get-XADServiceAccount() {
    Param (
        [Parameter(Mandatory=$true, 
                   Position=0,
                   ValueFromPipeline=$true,
                   HelpMessage="Identity of the ServiceAccount. NOTE: NT4 Style names such as: fabrikam\svcacct1"
                   )]
        [Object] $Identity,
        [Parameter(Mandatory=$false, 
                   Position=1,
                   HelpMessage="List of properties to fetch"
                   )]
        [Object] $Properties
    )
    Get-XADPrincipal -Identity $Identity -ObjectType "ADServiceAccount" -Properties $Properties
}


#
# Internal utility function
#
function GetServer() {
   Param ([String] $serverName)

   if ($serverName -ne $null -and $serverName -ne "") {
       $portSeparatorInd = $serverName.IndexOf(":")
       if ($portSeparatorInd -ge 0) {
           $serverName.SubString(0, $portSeparatorInd)
       } 
       else {
           $serverName
       }
   }
   else {
       $rootdse = get-adrootdse
       $rootdse.dnsHostName
   }
}

#
# Internal utility function
#
# Description: This is an utility function that acts as a or wrapper over Get-ADUser, Get-ADGroup etc. .
# Tested using: Windows 2008 R2 Beta.
#
function Get-XADPrincipal() {
    [CmdletBinding(ConfirmImpact="Low")]
    Param (
        [Parameter(Mandatory=$true, 
                   Position=0,
                   ValueFromPipeline=$true,
                   HelpMessage="Identity of the Principal. NOTE: NT4 Style names such as: fabrikam\administrator is acceptable"
                   )]
        [Object] $Identity,
        [Parameter(Mandatory=$true, 
                   Position=1,
                   ValueFromPipeline=$false,
                   HelpMessage="Type of the Principal. Supported types: G or ADGroup, U or ADUser, C or ADComputer, S or ADServiceAccount"
                   )]
        [String] $ObjectType,
        [Parameter(Mandatory=$false, 
                   Position=2,
                   HelpMessage="List of properties to fetch"
                   )]
        [Object] $Properties
     )
        
    BEGIN {
        if ($ObjectType -eq "ADUser" -or $ObjectType -eq "u") {
            $commandStr = "Get-ADUser "
        }
        elseif ($ObjectType -eq "ADGroup"-or $ObjectType -eq "g") {
            $commandStr = "Get-ADGroup "
        }
        elseif ($ObjectType -eq "ADComputer"-or $ObjectType -eq "c") {
            $commandStr = "Get-ADComputer " 
        }
        elseif ($ObjectType -eq "ADServiceAccount"-or $ObjectType -eq "s") {
            $commandStr = "Get-ADServiceAccount " 
        }
    }

    PROCESS {
        if ($Identity.GetType() -eq [String] ) {
            #
            # A valid NT4 style name would always contain backward slash \
            # Check if char '=' is not found .. so that we don't process DNs with \.
            #
            if ($Identity.Contains("\") -and ! $Identity.Contains("=") ) {
                $xNewServer,$xNewIdentity = $Identity.split("\", 2)
                $commandStr += " -Identity $xNewIdentity -Server $xNewServer " 
            }
            #
            # A valid UPN would always contain @
            # Check if char '=' is not found .. so that we don't process DNs with @.
            #
            elseif ($Identity.Contains("@") -and ! $Identity.Contains("=") ) {
                $xNewServer = (GetServer $null) + ":3268"     #Talk to a GC for cracking UPN names
                $xFilter = " { userPrincipalName -eq '$Identity' } "
                $commandStr += " -Filter $xFilter -Server $xNewServer " 
            } 
            else {
               $commandStr += " -Identity $Identity "
            }
        }
        else {
             $commandStr += " -Identity '" + $Identity.ToString() + "'"
        }
        if ($Properties -ne $null) {
            $commandStr += " -Properties $Properties "
        }
        $scriptBlock = [ScriptBlock]::Create( $commandStr )
        $scriptBlock.Invoke()
    }

    END {

    }
}

}

Update: Brandon Shell pointed out that Powershell has dropped the term "Script Cmdlets" and instead call them as "Advanced Functions". I have updated my post accordingly. He also pointed out few improvements to the script in terms of performance and brevity. I have updated the script with those changes. Thanks Brandon! 

Cheers!
Swami

--
Swaminathan Pattabiraman [MSFT]
Developer – Active Directory Powershell Team