Home > Software design >  Powershell | filter array with get-date
Powershell | filter array with get-date

Time:11-23

I have an array of staff data($employees) and in that array their is a field called start_date which is listed as a string. I am trying to filter out any staff member who's start_date is equal to the current month. Initially I thought I could had just wrote:

$employee | Where-Object {$_.start_date -ge Get-Date()}

Which didn't work.

I then tried to convert the Get-Date to a string with: 
$date = Get-Date -f '01/MM/yyyy'
$dateString = $date.toString

$employee | Where-Object {$_.start_date -ge $dateString}

Which also did not give me the results I was after also.

My Colleague who is fairly business with his work states, I might be best writing a foreEach-Object but I have always struggled how to write this, and don't wish to pull him away from his work to assist me on this task.

Example Array:

preferred_name    : John
name_suffixes     :
gender            : M
date_of_birth     : 09/05/1596
surname           : Doe
supervisor        : PRNMA01
start_date        : 28/11/2020
school_email      : [email protected]
teacher_code      :
termination_date  :
employee_photo    : @{file_info=}
supervisor_2      :
title             : Mr
driver_licence_no :
supplier_code     :
given_names       : John Jane

Task: Get the list of new staff and email the list to the department who looks after new staff training.

Any help on this would be good. Please ensure you explain in detail as i am not very bright in this field.

Thanks in advance.

CodePudding user response:

You can convert the start_date into datetime using parseexact and then compare the datetime objects directly.

$employee | Where-Object {[datetime]::parseexact($_.start_date, 'dd/MM/yyyy', $null) -ge (Get-Date)}
  • Related