如何计算 Powershell 中用户的年龄

How do I calculate the age of the user in Powershell

我正在尝试在 Powershell 中编写一个函数,根据生日计算用户的年龄。所以它可能应该是 currentdate - birthdate 并以年为单位计算差异。但是,我对这些日期的格式感到困惑,因为用户必须输入他们的生日。

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

首先你需要将输入参数$birthDate,目前是一个字符串,转换成一个DateTime object, for that you can use the ParseExact(..) method. Then you need to decide which type of date format your function will accept, I have added a ValidatePattern attribute to the function so that currently only accepts the pattern shown in your question, this however can be updated so that the function takes more than one format (ParseExact(..) can also parse multiple formats). Lastly, you're correct with Current Date - Birth Date, this will get us a TimeSpan object,它有一个.Days 属性,我们可以用属性的值除以一年中的天数得到用户的年龄

function getAge {
[cmdletbinding()]
param(
    [ValidatePattern('^(\d{2}-){2}\d{4}$')]
    [string]$birthDate
)

    $parsedDate = [datetime]::ParseExact(
        $birthDate,
        'dd-MM-yyyy',
        [cultureinfo]::InvariantCulture
    )

    [int] $age = ([datetime]::Now - $parsedDate).Days / 365
    Write-Host "Your age is $age"
}

getAge 24-01-1991

您的函数几乎完成了,除了它创建并 returns 一个具有当前日期和给定日期之间的差异的 TimeSpan 对象。

尝试

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))