Partilhar via


Extending Active Directory Powershell

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.

001002003004005006007008009010011012013014015016017018019020021022023024025026027028029030031032033034035036037038039040041042043044045046047048049050051052053054055056057058059060061062063064065066067068069070071072073074075076077078079080081082083084085086087088089090091092093094095096097098099100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224 ## URL: https://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

ActiveDirectoryExtension.ps1.txt

Comments

  • Anonymous
    March 20, 2009
    Today, I am going to show how we can leverage the power of Powershell V2 and Active Directory Module
  • Anonymous
    May 19, 2009
    In my previous post about Advanced filter s I showed how to use Powershell variables to represent values