1

I have a regex which returns the correct results when I use the various on-line regex testing sites. However when I use the regex in a PowerShell script, it only returns a single line instead of multiple lines. I'm the hoping PowerShell experts here can tell me what I'm doing wrong. I'm using PowerShell v1.

This is my regex: https://regex101.com/r/eA5jB2/3

This is my powershell script:-

#Read the file 
$FilePath = "testfile.txt" 

$regex = '(?msi)^0[12][VM](?:[^\n]|\n(?!0[12][VM]|50|90))+'
get-content $FilePath | select-string -pattern $regex 

The return is a single line

01Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  01 01 01

instead of

01Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 01 01 01
01=0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01=5xxxxxxxxxxxxxxxxxxxxxxxxxxx
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user3046742
  • 235
  • 1
  • 11

2 Answers2

1

The problem is in the Get-Content cmdlet, as it returns an array of lines, so you can't match the text divided by line break.

Try to use other method to get the file contents:

[IO.File]::ReadAllText($FilePath)
Get-Content $FilePath -Raw
Get-Content $FilePath | Out-String

You can find a similar question here.

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125
  • Thanks but when I try the first and last methods my script returns every possible line and the second isn't supported by powershell v1. All the methods work fine when I did "get-content $filepath | out-string >temp.txt" and copied the file into the online regex test site. – user3046742 Jan 15 '15 at 14:30
  • @user3046742 Those methods are just for reading the file in a way that you can apply your regular expression. You still need to pipe it into `Select-String`. – Ansgar Wiechers Jan 15 '15 at 20:37
0

I think the problem is using Select-String.

$text = 
@'
00 date
01Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01 01 01 01=0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01=5xxxxxxxxxxxxxxxxxxxxxxxxxxx
01Mxxxxxxxxxxxxxx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xxxxxxxxxxxxxx
01$0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
01$5xxxxxxxxxxxxxxxxxxxxxxxxxxx
***
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • That works fine! And it works when I read my file with "$text = get-content $FileName | out-string. Problem solved. – user3046742 Jan 15 '15 at 16:59