Created a Function to Search Through AD

Tagged: 

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Michael Orellana Michael Orellana 2 years, 2 months ago.

  • Author
    Posts
  • #19093
    Profile photo of Michael Orellana
    Michael Orellana
    Participant

    So I am pretty proud of this function, As its my first and it just feels good. Anyway my goal was to kind of dummy proof the ability search through AD objects for the other techs in my department using powershell without having to know the distinguished name of an OU and all that jazz. The parameters are specific to infrastructure so when specifying an OU the names can be auto populated to minimize fat fingering mistakes. Its still a work in progress and I want to add some error handling, but for right now it functions as I would like it to. But if you have any suggestions to make the code more efficient or anything id be happy to hear it.

    so here it is.

    function Search-ADObject 
    {
        [CmdletBinding()]
    
       Param(
                [Parameter (Mandatory=$true)]
                [ValidateSet('_Servers',
                             'Application_Accounts',
                             'Builtin',
                             'Campus_Austin',
                             'Campus_Co-Lo',
                             'Campus_FLEX',
                             'Campus_Online',
                             'Campus_Saint_Augustine',
                             'Campus_San_Marcos',
                             'Computers',
                             'Domain Controllers',
                             'Exchange Groups',
                             'Exchange Mailboxes',
                             'External Contacts',
                             'ForeignSecurityPrincipals',
                             'Groups',
                             'IT Personnel',
                             'Laureate',
                             'LostAndFound',
                             'Managed Service Accounts',
                             'Microsoft Exchange Security Groups', 
                             'Students',
                             'Students_inactive',
                             'Users')]
                [string]$OrganizationalUnit,
                
                [ValidateSet('_Servers',
                             '_Dev_Servers',
                             'Faculty',
                             'Library',
                             'Finance',
                             'Smart_Carts',
                             'Staff')]
                [string]$SubOrganizationalUnit, 
                
    
                [ValidateSet('Computers',
                             'Users')]
                [string]$Container,
    
                [Parameter (Mandatory=$true,ValueFromPipeline=$true)]
                [string]$Name,
                
                [string]$ErrorLog = "C:\Users\$env:USERNAME\Desktop\ScriptErrors.txt"
        )
    
    
     Process   
     {
            If(-not($Name)){ Throw "You must provide a value for -Name (use * to search for all objects in OU)" }
    
              $root = "DC=XXXXX,DC=XXX"
                
                If(-not($SubOrganizationalUnit)){
                        
                        $OuSearchBase = Get-ADObject -Filter {Name -eq $OrganizationalUnit} -SearchBase $root -SearchScope OneLevel |
                                            Select-Object -ExpandProperty DistinguishedName
                                               echo "============================================="
                                               Write-Host "You're searching within the $OuSearchBase OU" -ForegroundColor Cyan
                                               echo "============================================="
        
                          
                                Get-ADObject -Filter {ObjectClass -eq "User" -and Name -like $Name}  -SearchBase $OuSearchBase -SearchScope Subtree | Select-Object -ExpandProperty Name
                                    
                                    }
    
             
                 elseIf($SubOrganizationalUnit -and $Container){
                 
                        $OuSearchBase = Get-ADObject -Filter {Name -eq $OrganizationalUnit} -SearchBase $root -SearchScope OneLevel |
                                            Select-Object -ExpandProperty DistinguishedName  
                      
                            $OuSubBase = Get-ADObject -Filter {Name -eq $SubOrganizationalUnit} -SearchBase $OuSearchBase -SearchScope Subtree |
                                             Select-Object -ExpandProperty DistinguishedName
    
                                $OUcontain = Get-ADObject -Filter {Name -eq $Container} -SearchBase $OuSubBase -SearchScope Subtree |
                                                 Select-Object -ExpandProperty DistinguishedName    
                                                         
                                              
                                              echo "============================================="
                                              Write-Host "You're searching within the $OUcontain OU" -ForegroundColor Cyan
                                              echo "============================================="
                                     
    
                                Get-ADObject -Filter {ObjectClass -eq "User" -and Name -like $Name}  -SearchBase $OUcontain -SearchScope Subtree | Select-Object -ExpandProperty Name
    
                      
                                    }
                 
                 Else{ $OuSearchBase = Get-ADObject -Filter {Name -eq $OrganizationalUnit} -SearchBase $root -SearchScope OneLevel |
                                            Select-Object -ExpandProperty DistinguishedName  
                      
                            $OuSubBase = Get-ADObject -Filter {Name -eq $SubOrganizationalUnit} -SearchBase $OuSearchBase -SearchScope Subtree |
                                             Select-Object -ExpandProperty DistinguishedName
                        
                        
                                    Get-ADObject -Filter {ObjectClass -eq "User" -and Name -Like $Name} -SearchBase $OuSearchBase -SearchScope Subtree | Select-Object -ExpandProperty Name                    
                      
                                    }
                               
    
                          
            
        }
    }               
    
  • #19096
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Cool! 🙂 If I might offer one bit of feedback:

    echo "============================================="
    Write-Host "You're searching within the $OUcontain OU" -ForegroundColor Cyan
    echo "============================================="
    

    In PowerShell, "echo" is an alias for Write-Output. This means those strings containing all the equal signs are being sent to the pipeline. If you're only intending this function to display output to the screen, that might be okay, but more than likely you wanted another Write-Host call there instead of echo.

    Also, unless you always want that type of output displayed (with no way for the user to specify otherwise), you might consider swapping out the calls to Write-Host with calls to Write-Verbose instead. Then the user can control the level of output via the -Verbose switch or the $VerbosePreference variable.

  • #19097
    Profile photo of Michael Orellana
    Michael Orellana
    Participant

    Awesome thanks for the advice! I switched the echo's to Write-host as I always want the messages to be displayed.

You must be logged in to reply to this topic.