3

I am writing a script to get the results based on the user input, here user can give in date or date time... i need to get the results based on the input (date or datetime).

I have tried like below:

$StartDate  = Read-Host -Prompt 'Enter the start date of the logs, Ex: 17/07/2017 or 17/07/2017 09:00:00'

$culture = [Globalization.CultureInfo]::InvariantCulture

$pattern = 'dd\/MM\/yyyy HH:mm:ss', 'dd\/MM\/yyyy'

$params['After'] = [DateTime]::ParseExact($StartDate, $pattern, $culture)

getting the below error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
+     $params['After'] = [DateTime]::ParseExact <<<< ($StartDate, $pattern, $culture)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Please suggest, am i missing anything here.

0

3 Answers 3

5

I've had good luck using PowerShell's default Get-Date function on dates. I would try just using the following:

$StartDate = Get-Date (Read-Host -Prompt 'Enter the start date of the logs, Ex: 17/07/2017 or 17/07/2017 09:00:00')
Sign up to request clarification or add additional context in comments.

Comments

2

If you still would like to use ParseExact(), your issue was that $pattern was an array of strings rather than a string. You could check which pattern to use and then only pass that pattern.

$StartDate  = Read-Host -Prompt 'Enter the start date of the logs, Ex: 17/07/2017 or 17/07/2017 09:00:00'

$culture = [Globalization.CultureInfo]::InvariantCulture

if ($startdate -match '^\w\w\/\w\w\/\w\w\w\w$') {
    $pattern = 'dd\/MM\/yyyy'
} else {
    $pattern = 'dd\/MM\/yyyy HH:mm:ss'
}

$params['After'] = [DateTime]::ParseExact($StartDate, $pattern, $culture)

Comments

0

I would probably just use a short function; something like:

function Read-Date {
  param(
    [String] $prompt
  )
  $result = $null
  do {
    $s = Read-Host $prompt
    if ( $s ) {
      try {
        $result = Get-Date $s
        break
      }
      catch [Management.Automation.PSInvalidCastException] {
        Write-Host "Date not valid"
      }
    }
    else {
      break
    }
  }
  while ( $true )
  $result
}

Then you can write this:

Read-Date "Enter a date"

The code will prompt until the user enters a valid date-like string. Once the user enters a valid date string, the function's output is a [DateTime] object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.