I have a variable $datestring which contains a mixture of text and a date. This was pulled from the description field in AD. I would like to evaluate that and convert to date.
I tested a regular expression ‘\d{1,2}/\d{1,2}/\d{4}$’ that extracted the date.
I first tested it on a fully defined text expression to see if it worked.
You’ve put single quotes around $datestring, which is causing that text to be searched literally (not the value of the variable). If it’s already a string, no need to quote it:
$testString ="This account was created on 02/02/2016 by Bob."
$pattern = [regex]"(?'date'\d{1,2}/\d{1,2}/\d{4})"
if ($testString -match $pattern)
{
# examples of using the match, named and positional captures
$Matches['date']
"It happened on $($Matches[0])"
}
This pattern: ‘\d{1,2}/\d{1,2}/\d{4}$’ requires that the date be the very last thing in the string (that’s what the $ anchor at the end means). If your description field has any other characters after the date, even if they’re just whitespace, then it wouldn’t match. There also can’t be any whitespace within the date, such as ‘1 / 5 / 2014’. If you need to handle those sorts of things, then the pattern needs to be tweaked slightly.