1

Hoping an experienced coder could explain why a variable create from contents of a text file and added to a match pattern does not work...but a variable with a static string does?

$computer = "TYMXL-F3MC012WV"

$s_01 =  (Get-Content $path\source_files\pascodes.txt -Raw).replace("`n","|") #F3MC|FRSE|FGTS
$s_02 = "F3MC|FRSE|FGTS"

$computer -match "^(TYMX|MPLS)(W|L|T|V)-($s_01)([a-zA-Z0-9]{1}).+$" #false
$computer -match "^(TYMX|MPLS)(W|L|T|V)-($s_02)([a-zA-Z0-9]{1}).+$" #true
jaco0646
  • 15,303
  • 7
  • 59
  • 83

1 Answers1

0

Your text file likely uses CRLF ("`r`n") newlines rather than LF-only ("`n") newlines, so that replacing just the latter isn't enough.

A simple way to avoid this problem is to not use -Raw, so that Get-Content returns an array of lines, which you can the join with |:

$s_01 = (Get-Content $path\source_files\pascodes.txt) -join '|'

Note that Get-Content recognizes CRLF and LF newlines interchangeably, as does PowerShell in general.


While you could fix your original attempt as follows, the above solution is much simpler (while it is slower, that won't matter with small files):

$s_01 = (Get-Content $path\source_files\pascodes.txt -Raw).Trim() `
          -replace '\r?\n' , '|'
  • The regex \r?\n used with the -replace operator above matches both CRLF and LF newlines.

  • .Trim() is applied first in order to remove any trailing newline, so that it doesn't also get replaced with |; note that this trims all leading and trailing whitespace; to trim just a single trailing newline, use -replace '\r?\n\z' instead (before applying the -replace operation above).

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    mklement0, Thanks for taking the time in explaining in why mine will not work and how yours does.. I included your examples below to show others how there are multiple ways of using a list of values in a text file and creating a logical 'or' group to place in a regex pattern. Thanks for the help! – Boris Pumpernickel Aug 30 '21 at 15:04
  • Sorry all...have no idea how to add code tags...even with help example...but answers provides above both work in my situation...and looks like i inadertently deleted your comment mklement0...meant no disrespect – Boris Pumpernickel Aug 30 '21 at 15:15
  • @BorisPumpernickel, re my deleted comment: No worries at all: I deleted it myself once I knew you had seen it (I appreciated your nice feedback and wanted to acknowledge it, but I figured the comment had served its purpose once you had read it). – mklement0 Aug 30 '21 at 15:19
  • @BorisPumpernickel, as for formatting in comments: see https://stackoverflow.com/help/formatting - in short: you can only use _inline_ code formatting (`\`...\``) with no support for line breaks, and you cannot _double_ `\`` instances - use `\\`` to embed `\``. – mklement0 Aug 30 '21 at 15:19