Search-String & Finding Number Variances

I’m not 100% sure if this is the right way to go about a task I have so I need a sanity check.

In a nutshell, I have a log that I generate from an app that contains a specific line, “Data Expiry:[some white space]XX days” where XX is going to be a varying number. I need to somehow detect that number when it’s 10 or less. I also need to export as a variable whatever that number is so it can be added to an event log entry.

I’m dreading having to possibly do this with RegEx, is there a more efficient way to go about this?

You could always make a substring out of it.

$data = "Data Expiry:    12 days"

$start = $data.IndexOf(':') + 1
$end = $data.IndexOf(" days")
$length = $end - $start
[int]$num = $data.Substring($start,$length).TrimStart(" ")
$num

Statically casting $num to an integer allows you to compare $num to other integers (i.e. if ($num -le 10) {do something})

Thanks I’ll give this a try.

A good overview of what’s possible you can find here: Sophisitcated Techniques of Plain Text Parsing

That did exactly what I was looking for with a little tweaking. Thanks again!

Thank you for that link, I’ve added this to my playlist and will watch soon. Almost all of the scripts I’ve had to create this year for co-workers have involved parsing text files. Most of them have been really easy but I’ve been getting some really intense requests for very specific data that I’m just not used to gathering with PowerShell yet. This looks like it will help me a lot.

$data = "Data Expiry:    12 days"
[int]$num = $data.Split(@('Data Expiry:'),0).Trim().Split(@('days'),0)[1]
"The number is ($num)"

BTW: Why do you actually think regex would be less efficient than other approaches? :wink:

$data = “Data Expiry:    12 days”
$data -match ‘Expiry:\s+(\d+)\s+days’ | Out-Null
[INT]$num = $Matches[1]
$num

I try to avoid RegEx if at all possible in favor of native PowerShell methods. I also have a heavy bias against using RegEx because A) I find it to be too cryptic for the next person reading my script. B) I don’t like using it, have a really hard time with all the syntax.

Like awk or cut. -split works with variable whitespace:

PS /Users/js> 'Data Expiry:    12 days' | foreach { -split $_ | select -index 2 } 

12