0

I am trying to parse filenames (strings) and convert them to dates in powershell using the following line:

([datetime]::ParseExact($DirName.BaseName,'yyyyMMdd',$null)

The problem is, not all of the folders in that directory following that naming convention. How would I first test to see if the folder fits the naming convention and if it does, convert it to a date time object? Any help would be greatly appreciated.

1
  • Use RegEx. That way you could detect different patterns and act on them with specific solutions. Commented Jun 25, 2016 at 7:49

1 Answer 1

2

I wouldn't bother checking first. Just put the call in a try..catch block. I would recommend using InvariantCulture rather than $null, though.

$culture = [Globalization.CultureInfo]::InvariantCulture
try {
  [datetime]::ParseExact($DirName.BaseName, 'yyyyMMdd', $culture)
} catch {
  # not a valid date
}
Sign up to request clarification or add additional context in comments.

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.