Michael
Michael

Reputation: 132

search file and then return part of the line below

I'm trying to use PowerShell to search a file for a string then return part of the string that is on the next line.

The file would be like: LTI.ini

Division=AAA-
TargetContainer=OU=Computers,OU=123,DC=ms,DC=com

Division=BBB-
TargetContainer=OU=Computers,OU=456,DC=ms,DC=com

So I have so far is

$name = 'BBB-1234'
$pos = $name.IndexOf("-")
$leftPart = $name.Substring(0, $pos) + '-'

$a = Get-Content ..\Desktop\Powershell\LTI.ini
$b = $a | Select-String $leftPart
$b

This gives me $b as the BBB- line from the LTI.ini, but I don't know how to set the following line to a variable, and then only grab everything after TargetContainer=

Upvotes: 0

Views: 175

Answers (2)

Andy Arismendi
Andy Arismendi

Reputation: 52609

Here is the multiline regex @JPBlanc mentioned:

$regex = "${leftPart}(.+)(TargetContainer=)(.+)Division="
[regex]::Matches($a, $regex, 'Singleline')[0].Groups[3].Value.Trim()

Upvotes: 0

CB.
CB.

Reputation: 60918

This should work:

$b =($a | select-string $leftpart -Context 1  ).context.postcontext -replace '(?:TargetContainer=)(.*)','$1'
$b

Upvotes: 4

Related Questions