Home > Software engineering >  How do I read a substring from a txt file?
How do I read a substring from a txt file?

Time:09-18

(Select-String -Path "C:\Testfile\loadService.ini" -Pattern ("Server =(.*)", "DBName =(.*)")).Matches.Groups[1].Value

I want to output the information after Server = and DbName= and I cannot get this to run.

CodePudding user response:

as you have two patterns you have to get each value using foreach

(Select-String -Path ./test.ini -Pattern ("Server =(.*)","DbName =(.*)")).Matches | Foreach-Object {$_.Groups[1].Value}

CodePudding user response:

  • Whenever capture groups are involved and more than one line matches, the [Microsoft.PowerShell.Commands.MatchInfo] objects that Select-String outputs must be processed one by one.

  • If -AllMatches were involved (it isn't here), you'd additionally have to process the entries of the .Matches collection one by one. In the absence of -AllMatches there is by definition only one match per matching line, stored in .Matches[0]

Therefore:

Select-String -Path "C:\Testfile\loadService.ini" -Pattern ("Server =(.*)", "DBName =(.*)") |
  ForEach-Object { $_.Matches[0].Groups[1].Value }

Note: Given that $_.Matches by definition only has 1 element, you could get away with omitting the [0] in this case, using member-access enumeration.

However, you can not use member enumeration directly on the multi-object Select-String output, as you've attempted ((Select-String ...).Matches.Groups[1].Value, because the nested .Groups[1] access would only be applied once across all output objects, namely to the single, flat collection of match objects collected from the .Matches collections of the individual output objects.

  • Related