PowerShell:- List – Sorting

Background

Imagine it is mother’s day and we need to fetch our Mother of the Church.

Yes, just do a simple select against your congregation table.

But, was exploring something similar in PowerShell.

Here is what our code line looks like.

 

Script

 

Outline

    1. Class
      • Create a simple class structure
      • In our case we our class name is person
    2. List
      • Instantiate a collection class
        • The name of the class is System.Collections.ArrayList
    3. Add persons to the collection
    4. Display Output
      • List all persons
        • List all persons ordered by name
      • Fetch oldest person
        • Sort
          • Sort by dob ( in ascending order )
        • Fetch first element post sorting using “select -first 1
        • Project attributes
          • name:-
            name 
          • date of birth:-
            @{Name = "date of birth"; Expression = { "{0:yyyy-MMM-dd}" -f ($_.dob ) } } 
          • gender:-
            gender
          • Age:-
             @{Name = "age"; Expression = { ( $_.age) } } 
      • Fetch oldest living person
        • Filter out records that have valid dateofLeaving date
          • Use where-object to review dateofLeaving
             Where-Object { ( $_.dateofLeaving -eq $null ) } 
      • Fetch mothers only
        • Leave in only records whose gender is Female
          • Use where-object to review gender
             Where-Object gender -eq "F" 

Code


Set-StrictMode Version Latest
<#
Declare Person Object
#>
class person
{
[string] $name;
[datetime] $dob;
[Nullable[DateTime]] $dateofLeaving;
[char] $gender;
[int] $age;
}
<#
Declare Variables
#>
[System.Collections.ArrayList] $listofPersons = $null;
[string] $title = "";
[int] $numberofPersonsToFetch =0;
<#
Set Variables
#>
$numberofPersonsToFetch =1;
<#
Instanciate Collection ( $listofPersons )
#>
$listofPersons = New-Object TypeName "System.Collections.ArrayList";
<#
Function:- addPerson
#>
function addPerson
(
[string] $name `
, [datetime] $dob `
, [char] $gender `
, [Nullable[DateTime]] $dateofLeaving
)
{
<#
Declare local variables
#>
[Nullable[DateTime]] $dtReferenceAge = $null;
<#
Instanciate person object
#>
$obj = [person]::new();
<#
Set Class Property
#>
$obj.name = $name;
$obj.dob = $dob;
$obj.gender = $gender;
<#
If date of leaving is indicated
please use the date provided as base for calculating age
else
use current date
#>
if ($dateofLeaving -ne $null )
{
$obj.dateofLeaving = $dateofLeaving;
$dtReferenceAge = $dateofLeaving;
}
else
{
$dtReferenceAge = [datetime]::Now;
}
<#
https://stackoverflow.com/questions/14959399/powershell-getting-a-persons-age
#>
<#
Get timestamp between reference date and dob
#>
$span = $dtReferenceAge $dob
$ageSpan = New-Object DateTime ArgumentList $Span.Ticks;
$obj.age = $ageSpan.year -1;
$ageSpan = $null;
$null = $listofPersons.add($obj);
}
function displaySectionHeader([string] $title)
{
[int] $len =0;
[char] $CHAR_HYPHEN = "";
[string] $underline ="";
$len = $title.length;
$underline = [String]::new($CHAR_HYPHEN, $len);
Write-Host $title;
Write-Host $underline;
}
<#
Add persons
https://en.wikipedia.org/wiki/Mae_Jemison
#>
$null = addPerson "Mae Jemison" "1956-10-17" "F" $null
#https://en.wikipedia.org/wiki/Ricki_Lake
$null = addPerson "Ricki Lake" "1968-12-21" "F" $null
# https://en.wikipedia.org/wiki/Lauren_Lake
$null = addPerson "Lauren Lake" "1969-07-12" "F" $null
# https://en.wikipedia.org/wiki/John_Lewis
$null = addPerson "John Lewis" "1940-02-21" "M" "2020-06-17"
# https://en.wikipedia.org/wiki/Sidney_Poitier
$null = addPerson "Sidney Portier" "1927-02-20" "M" "2022-01-06"
<#
List all persons
#>
$title = "Persons";
displaySectionHeader $title;
$listofPersons|
select name, dob, gender, dateofLeaving |
Sort name |
Format-Table * AutoSize
Write-Host "";
Write-Host "";
<#
Get oldest person
a) based on date of birth
#>
$title = "Oldest Person";
displaySectionHeader $title;
$listofPersons|
Sort dob |
select first ($numberofPersonsToFetch)`
name `
, @{Name = "date of birth"; Expression = { "{0:yyyy-MMM-dd}" -f ($_.dob ) } } `
, @{Name = 'gender'; Expression = {"{0,-6}" -f ($_.gender ) }}`
, @{Name = "date of leaving"; Expression = { "{0:yyyy-MMM-dd}" -f ($_.dateofLeaving ) } } `
, @{Name = "age"; Expression = { ( $_.age) } } |
Format-Table * AutoSize
Write-Host "";
Write-Host "";
<#
Get oldest person
a) based on date of birth
b) filter out departed
#>
$title = "Oldest Person – Leave out departed";
displaySectionHeader $title;
$listofPersons|
Where-Object { ( $_.dateofLeaving -eq $null ) } |
Sort dob |
select first ($numberofPersonsToFetch)`
name `
, @{Name = "date of birth"; Expression = { "{0:yyyy-MMM-dd}" -f ($_.dob ) } } `
, @{Name = 'gender'; Expression = {"{0,-6}" -f ($_.gender ) }}`
, @{Name = "age"; Expression = { ( $_.age) } } |
Format-Table * AutoSize
Write-Host "";
Write-Host "";
<#
Get oldest person
a) based on date of birth
b) filter out departed
d) only females
#>
$title = "Oldest Person – Leave out departed, Gender has to be female";
displaySectionHeader $title;
$listofPersons|
Where-Object { ( $_.dateofLeaving -eq $null ) } |
Where-Object gender -eq "f" |
Sort dob |
select first ($numberofPersonsToFetch)`
name `
, @{Name = "date of birth"; Expression = { "{0:yyyy-MMM-dd}" -f ($_.dob ) } } `
, @{Name = 'gender'; Expression = {"{0,-6}" -f ($_.gender ) }}`
, @{Name = "age"; Expression = { ( $_.age ) } } |
Format-Table * AutoSize

Output

Output – Image

Output – Text


>powershell ./person.ps1
Persons
-------

name           dob                    gender
----           ---                    ------
John Lewis     2/21/1940 12:00:00 AM       M
Lauren Lake    7/12/1969 12:00:00 AM       F
Mae Jemison    10/17/1956 12:00:00 AM      F
Ricki Lake     12/21/1968 12:00:00 AM      F
Sidney Portier 2/20/1927 12:00:00 AM       M




Oldest Person
--------------

name           date of birth gender age
----           ------------- ------ ---
Sidney Portier 1927-Feb-20        M




Oldest Person - Leave out departed
-----------------------------------

name        date of birth date of leaving gender age
----        ------------- --------------- ------ ---
Mae Jemison 1956-Oct-17                        F  65




Oldest Person - Leave out departed, Gender has to be female
------------------------------------------------------------

name        date of birth date of leaving gender age
----        ------------- --------------- ------ ---
Mae Jemison 1956-Oct-17                        F  65



>


Source Code

  1. GitHub
    • Gist
      • DanielAdeniji/personListSortedByAge.ps1
        Link
  2. GitLab
    • Snippets
      • PowerShell:- Grouping and Sorting
        • listPersonOrderBy.ps1
          Link

 

Listening

Just like that, I am back on these streets.

Saweetie – Back to the Streets (feat. Jhené Aiko)
Link

 

Dedication

Always in dedication to those that care and lift up the people of God.

Sidney Poitier ( 1968 )

 

Mae Jamison ( 1992 )

John Lewis ( 1992 )

 

Referenced Work

  1. Sidney Poitier
    Link
  2. Mae Jamison
    Link
  3. John Lewis ( Congress Man – The Good Fight )
    Link

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s