Author Posts

April 27, 2017 at 6:59 pm

1).Every 15 minutes between 3:00am and 9:00pm every day
2)Every 2 hour(s) between 6:30:00 AM and 9:30:00 PM.
3)Every hour between 6:30:00 AM and 9:30:00 PM.
4)Runs at 4:30am, noon, and 4 PM.

I have strings like above
I want to get time from those strings like below
1). 15 minutes, 3:00 am , 9:00 pm
2).2 hours, 6:30:00 AM,9:30:00 PM.
3). hour, 6:30:00 AM,9:30:00 PM.
4).4:30am, noon ,4 PM

I have tried using $Time.Split("")[4] +" "+ $Time.Split("")[5] but it did not work because the string is changing in all the formats

So i wanted to find time time in the string.

But no idea.need help on this

April 27, 2017 at 9:21 pm

To do this you need to use regular expressions. If those are the only string formats you have then I think it's actually going to be easier to replace the text you don't want rather than search for the text you're after – it took me less time to figure out how to do it that way 🙂

Get-Help about_regular_expressions

$strings = 'Every 15 minutes between 3:00am and 9:00pm every day','Every 2 hour(s) between 6:30:00 AM and 9:30:00 PM.','Every hour between 6:30:00 AM and 9:30:00 PM.','Runs at 4:30am, noon, and 4 PM.'

foreach ($string in $strings) {

    $string = ($string -replace "Every|Between|and|day|Runs|at|\.|\,"," ").trim() -replace "\s{2,}",","    

    Write-Output $string
}

April 28, 2017 at 1:31 am

I agree with Matt. Removing what you don't need is sometimes preferable. Otherwise you could be stuck with maintaining this:

$strings = 'Every 15 minutes between 3:00am and 9:00pm every day','Every 2 hour(s) between 6:30:00 AM and 9:30:00 PM.','Every hour between 6:30:00 AM and 9:30:00 PM.','Runs at 4:30am, noon, and 4 PM.'

foreach ($string in $strings) {
    (([regex]::Matches($string, '(\d:?(?:\d{2})?(?::\d{2})?\s?(?:[a|p]m))|\d?\d?\s?(?:hour(?:\(s\))?|minutes?|noon)', @('IgnoreCase'))).Value).Trim()
}

May 1, 2017 at 3:10 pm

Thanks Matt thats a cool code it helps

May 1, 2017 at 3:11 pm

Thanks Roy I will give this a try if it works as it is simple