Isolate Date in string

I am trying to isolate the date in a string, the string is non-standard and can be be an number or character before and after the date but the date is in a semi-standard format similar to 1/9/2012 or 01/09/2012.

I will need to isolate it so I can compare the date to the current date and take an action.

Example string: ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757

Thank you
patrickm12981Asked:
Who is Participating?
 
footechConnect With a Mentor Commented:
More of an aside, but the syntax in the last line of the example from StackOverflow is wrong.
       $dateTime -f 'MM/dd/yyyy HH:mm:ss'
$dateTime -f '' (those are two single quotes) or any variation of items to the right of "-f" would give the same result.  It should be
'{0:MM/dd/yyyy HH:mm:ss}' -f $dateTime

Anyway, the first example given would only match a date in the form of "xx/xx/xxxx jkslajfksa;ejf3:sadfsds:sadfsdf;  : " (where x is any single digit).  The colon-space at the end is important.  Unfortunately that nonsense string I just typed would match.  The regex pattern was constructed to try to also match hours, minutes, and seconds from the line in the example.

The second example (from oBdA) narrows down the regex pattern to only look for a date, but it's still looking for the pattern "xx/xx/xxxx".

Since you mentioned that the date may vary in its format, we'd need to know what all the possible variations are.  Hopefully the example string you posted is representative of the fact that there are no similar portions of the string with the same format as the date.
Here's a regex pattern that should match given the variability that you've mentioned so far.
"\s(\d{1,2}/\d{1,2}/\d{4})\s"
You could even construct a regex pattern that would limit the matches further to only valid numbers for months, days, and a range of years, but that's probably overkill.
$line = "ABC;12345;IU:TYU; Disabled 5/5/2012 CB00757"
If ($line -match "\s(\d{1,2}/\d{1,2}/\d{4})\s")
{
    $dateTimeString =  Get-Date($matches[1])
    If ($dateTimeString -lt (Get-Date))  #example of a condition check
    { write-output "I'm gonna do something!" }
}

Open in new window

0
 
Randy DownsOWNERCommented:
Maybe this will help. Their example is looking for dates in the format 05/22/2012

http://stackoverflow.com/questions/10710950/powershell-extract-timestamp-from-string


... parse out the date/time string with a regular expression and then convert it to a date/time object:

$line = 'C:\Documents and Settings\admin\Local Settings\Application Data\Microsoft\SyncToy\2.0\SyncToyLog.log:325:SYNC: 05/22/2012 14:54:55:857: SyncToy run of Profile Backup (C:\Documents and Settings\admin\, H:\Sync\) completed at 5:22/2012 2:54:55 PM.'

$dateTimeString = [regex]::Matches($line, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[1].Value

Then convert it to a datetime object:

$provider = New-Object System.Globalization.CultureInfo "en-US"

$dateTime = [datetime]::ParseExact($dateTimeString, 'MM/dd/yyyy HH:mm:ss:fff', $provider)

Now you can display it or store it in a variable however you want:

$dateTime -f 'MM/dd/yyyy HH:mm:ss'

0
 
patrickm12981Author Commented:
I tried that example, it didn't work for me.
0
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

 
Randy DownsOWNERCommented:
Does it find any of the dates?
0
 
patrickm12981Author Commented:
No.

$line = "ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757"
$dateTimeString = [regex]::Matches($line, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[1].Value
$provider = New-Object System.Globalization.CultureInfo "en-US"
$dateTime = [datetime]::ParseExact($dateTimeString, 'MM/dd/yyyy HH:mm:ss:fff', $provider)
$dateTime -f 'MM/dd/yyyy HH:mm:ss'
Write-Host  $dateTime.

Open in new window


Cannot index into a null array.
At E:\Scripts\User_Delete\test.ps1:2 char:81
+ $dateTimeString = [regex]::Matches($line, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[ <<<< 1].Value
    + CategoryInfo          : InvalidOperation: (1:Int32) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At E:\Scripts\User_Delete\test.ps1:4 char:35
+ $dateTime = [datetime]::ParseExact <<<< ($dateTimeString, 'MM/dd/yyyy HH:mm:ss:fff', $provider)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Open in new window

0
 
Randy DownsOWNERCommented:
Try single quotes

$line = 'ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757'
0
 
patrickm12981Author Commented:
No Change.
0
 
oBdACommented:
Try
$StringRaw = "ABC;12345;IU:TYU; Disabled 05/25/2012 CB00757"
If ($StringRaw -match '\d\d/\d\d/\d\d\d\d') {
	$StringDateTime = [datetime]::ParseExact($Matches[0], 'MM/dd/yyyy', [System.Globalization.CultureInfo]::GetCultureInfo("en-US"))
	Write-Output "Date identified from string `'$StringRaw`': $StringDateTime"
} Else {
	Write-Error "Could not identify a date in string `'$StringRaw`'."
}

Open in new window

0
 
footechCommented:
BTW, I was messing around and came up with a regex pattern to do some validation of the date (what else am I supposed to do on a Saturday night?).  It handles the number of days correctly for each month, with the slight exception of February, where it always allows up to 29 days regardless of whether it's a leap year or not, and it allows years in the range 1900-2099 (didn't bother to account for the possibility of two-digit years).  It works for both single digit days and months or zero-padded.
"\b((((0?[469])|(11))/((0?[1-9])|([12]\d)|(30))|((0?[13578])|(1[02]))/((0?[1-9])|([12]\d)|(3[01]))|(0?2/(0?[1-9])|([12]\d)))/((19\d{2})|(20\d{2})))\b"

Open in new window

0
 
patrickm12981Author Commented:
Thank you footech - that worked like a charm
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.