How to string to date RRS feed

  • Question

  • I developed a Powershell script where the user must enter a date dd/mm/yyyy.

    A part the script is this:

    $Date = Read-Host -Prompt 'Enter the end of contract date - dd/mm/yyyy'
    Set-ADAccountExpiration -Identity $SamAccountName -DateTime $Date -Server (Get-ADDomain).PDCEmulator

    If the date is entered correctly, the script works. But if a non-existent date is entered, example 31/02/2020, it gives an error:

    Set-ADAccountExpiration: Cannot bind parameter 'DateTime'. Cannot convert value "31/02/2020" to type "System.DateTime". Error: "String was not recognized as a valid DateTime. "

    At C: \ Users \ Administrator \ Documents \ tests \ Versions \ Create_user_account.ps1: 58 char: 61

    + ... ccountExpiration -Identity $ SamAccountName -DateTime $ ExpDate -Server ...

    + ~~~~~~~~

    + CategoryInfo: InvalidArgument: (:) [Set-ADAccountExpiration], ParameterBindingException

    + FullyQualifiedErrorId: CannotConvertArgumentNoMessage, Microsoft.ActiveDirectory.Management.Commands.SetADAccountExpiration

    How best to treat/manipulate this?


    Friday, November 20, 2020 6:38 PM