1 Replies - 2607 Views - Last Post: 27 June 2012 - 09:02 AM Rate Topic: -----

#1 webmin88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 22-October 11

Validate Date Using Powershell

Posted 27 June 2012 - 07:58 AM

Hey folks,

Trying to validate that a date entered is correct using powershell. So far this is what I have:

function ValidateDate
{
    param([string]$date=$_)
    $result = 0
    [bool]$valid = $false
    if (!([DateTime]::TryParse($date, [ref]$result))){
        Write-Host "Your date $date was invalid. Please try again."
        $date = Read-Host "Please enter the date with the following format mm/dd/yy: "
        ValidateDate $date
    }
    else{$valid = $true}
    Return $valid
}



When running the script, I enter a wrong date on purpose, it prompts me to revise the date, and then it should return a true value once the date is correct. Unfortunately this is the output I get:

PS C:\Users\bvandermark> ValidateDate 6/51/12
Your date 6/51/12 was invalid. Please try again.
True
False

Not sure why the false is there as well. Any thoughts?

Is This A Good Question/Topic? 0
  • +

Replies To: Validate Date Using Powershell

#2 webmin88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 22-October 11

Re: Validate Date Using Powershell

Posted 27 June 2012 - 09:02 AM

Never mind. Resolved this on my own.

The trick was to include the Return $valid in the else statement.

function ValidateDate
{
    param([string]$date=$_)
    $result = 0
    [bool]$valid = $false
    if (!([DateTime]::TryParse($date, [ref]$result))){
        Write-Host "Your date $date was invalid. Please try again."
        $date = Read-Host "Please enter the date with the following format mm/dd/yy: "
        ValidateDate $date
    }
    else{
        $valid = $true
        Return $valid
    }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1