How can I calculate a persons age in Powershell

Ian 35 Reputation points
2024-06-18T15:23:58.28+00:00

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 ?

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

Accepted answer
  1. Ian Xue 37,541 Reputation points Microsoft Vendor
    2024-06-18T23:50:10.2933333+00:00

    Hi Billy the Mexican,

    Thank you for posting on Microsoft Q&A.

    You can use the DateTime.ParseExact method.

    https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact

    $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. Ian 35 Reputation points
    2024-06-19T09:38:20.1433333+00:00

    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


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.