How can I calculate a persons age in Powershell

Billy the Mexican 25 Reputation points

I very new to Powershell so appologise for probably asking a very basic question.

I need to write a script to show how old a member of staff is in years and months.

I need to convert a string that is in the format of "25-09-1973" to a date format so I can then subtract it from todays date but everything I try is coing out wrong.

Two days of Googling has not helped me write the script how I want it to appear as I can not do the maths on the dates.

Can anybody help me out ?

A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,300 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 34,111 Reputation points Microsoft Vendor

    Hi Billy the Mexican,

    Thank you for posting on Microsoft Q&A.

    You can use the DateTime.ParseExact method.

    $dateString = '25-09-1973'
    $date = [datetime]::ParseExact($dateString,'dd-MM-yyyy',[CultureInfo]"en-US")
    $age = [datetime]::Now - $date

    Best Regards,

    Ian Xue

    If the Answer is helpful, please click "Accept Answer" and upvote it.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Billy the Mexican 25 Reputation points

    Thanks for pointing me in the right direction, I have followed your instructions and am nearly there as I can divide the number of days by 365 and I get the how old the person is in number of years.

    Does PowerShell have a built in function to show how many months have passed since a certain date?

    I was going to try and write a script to calculate this but thought that PowerShell may already do this.Powershell_Calculate_Age