Reputation: 25
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.
Upvotes: 0
Views: 1574
Reputation: 200203
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
}
Upvotes: 2