Author Posts

December 29, 2017 at 6:57 pm

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?

December 29, 2017 at 7:18 pm

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})

December 29, 2017 at 7:45 pm

Thanks I'll give this a try.

December 29, 2017 at 11:37 pm

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

December 30, 2017 at 1:10 am

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

December 30, 2017 at 1:12 am

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.

December 30, 2017 at 4:55 am

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

December 30, 2017 at 3:17 pm

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

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

December 30, 2017 at 4:48 pm

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.

December 31, 2017 at 4:04 pm

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

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

12