[SOLVED] How do I calculate the age of the user in Powershell

Issue

I’m trying to write a function in Powershell where I calculate the age of the user based on the birthdate. So it should probably be currentdate – birthdate and put the difference in years. I’m getting stuck however, on the formating of these dates because the user has to input their birthdate.

Function getAge ($birthDate)
{
    $currentDate = Get-Date
    $age = $currentDate - $birtDate
    Write-Host "Your age is $age"
}
getAge 24-01-1991

Solution

Your function is almost there, except for the fact that it creates and returns a TimeSpan object with the difference between the current and the given date.

Try

function Get-Age {
    param (
        [Parameter(Mandatory = $true)]
        [datetime]$birthDate
    ) 
    $currentDate = Get-Date
    $age = $currentDate - $birthDate

    # use the ticks property from the resulting TimeSpan object to 
    # create a new datetime object. From that, take the Year and subtract 1
    ([datetime]::new($age.Ticks)).Year - 1
}

# make sure the BirthDate parameter is a valid DateTime object
Get-Age ([datetime]::ParseExact('24-01-1991', 'dd-MM-yyyy', $null))

Answered By – Theo

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *