Search code examples
powershellactive-directory

Find highest value in Get-ADOrganizationalUnit Name


I am currently using:

Get-ADOrganizationalUnit -LDAPFilter '(name=Students 20*)' -SearchBase 'OU=Students,OU=VAL Accounts,DC=VAL,DC=VAL,DC=VAL,DC=au' | ft Name

Which generates the following:

Students 2009
Students 2010
Students 2011
Students 2012
Students 2013
Students 2014
Students 2015
Students 2016
Students 2017
Students 2018
Students 2019

I wish to get the highest year and save it as a value to use later in the program.

I.E: $value = 'Students 2019'

As 2019 is the highest number in the list


Solution

  • You can add a property to the objects to represent the year. Something like:

    $OUs = Get-ADOrganizationalUnit -LDAPFilter '(name=Students 20*)' -SearchBase 'OU=Students,OU=VAL Accounts,DC=VAL,DC=VAL,DC=VAL,DC=au' | 
    Select-Object *,@{Name = 'OU_Year'; Expression = { $_.Name.Split(' ')[1] }} 
    
    $LatestYear = ($OUs | Sort-Object OU_Year | Select-Object -Last 1).OU_Year
    

    $LatestYear should be 2019.

    This works by compiling your list, doing a sort of the list, and reporting just the last instance.