0

I have a regex query working in regexr but it will not work for me in PowerShell. What am I doing wrong?

regex

(Host.*[\r\n]+([^\r\n]*)+[\r\n]+([^\r\n]*))

Data

HostName: ComputerName
Date: 2018-12-21
Time: 09:16:02
Step: 01
Date: 2018-12-21
Time: 09:29:18
Step: 02
Date: 2018-12-21
Time: 09:47:38
Step: 03
Date: 2018-12-21
Time: 10:08:43
Step: 04
Date: 2018-12-21
Time: 10:27:00
Step: 05
Date: 2018-12-21
Time: 10:45:14
Step: 06
Date: 2018-12-26
Time: 10:02:39

On match it captures the rest of the line and the next two lines. Since everything is in groups of 3 per entry in the log.

I pasted the working code in powershell and attempted the three ways.

$data | select-string -match "(Host.*[\r\n]+([^\r\n]*)+[\r\n]+([^\r\n]*))"

$data -matches "(Host.*[\r\n]+([^\r\n]*)+[\r\n]+([^\r\n]*))"

I've done research and the closest thing I can get is that windows doesn't play nice with \r\n.

I haven't found a solution yet.

What am I doing wrong or what do I need to replace \r\n with?

8
  • What is the output of $data.GetType().FullName? Commented Jan 8, 2019 at 15:39
  • Result of GetType is System.Object[] Commented Jan 8, 2019 at 15:46
  • Data Was Gathered via Get-Content Commented Jan 8, 2019 at 15:46
  • 1
    Keep in mind that if you use Get-Content without the -Raw switch you'll end up with an array of strings instead of a single string (with linebreaks) Commented Jan 8, 2019 at 15:49
  • do you just want the 1st 3 lines? that is all that regexr shows being captured. if so, there are simpler ways to grab lines 0-2 ... Commented Jan 8, 2019 at 15:51

1 Answer 1

1

Your data isn't what you expect. Get-Content reads files into an array of lines and removes the line breaks from the end of each line. Both Select-String and -match check each line separately against the regular expression, but can't find a match, because each line contains only a fraction of what you want matched.

To fix the issue you need the entire content of the file as a single string.

$data = Get-Content 'C:\path\to\input.txt' | Out-String

On PowerShell v3 or newer you could also use

$data = Get-Content 'C:\path\to\input.txt' -Raw
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.