Don B
Don B

Reputation: 1

Selecting Text In between strings

I am trying to parse some text between strings of output.

I've tried using -split and substring but I am not getting the correct output

Here are the input file/Pipeline values

Please remove the following Roles:
Role1
Role2

Please remove the following Groups:
Groups1
Groups2

Please remove the following Profiles:
Profiles1
Profiles3
Profiles8

Please remove the following DGroups:
DG1
DG9
DG12

Here is the code I tried

Foreach($input in $file){
#I’ve tried the split and I get too much data after roles
write-host $input.split(':')[1]
#replace gives me too much info after roles
$input.replace('Please remove the following Roles:','')
#this loop will continuously run
do{
$input}
until{$input.contains("please*")}
}

I expect the output to give me Role1 and Role2, then groups1 and groups2, then profiles1 and profiles3 and profiles8, then dg1 and dg9 and dg12 then ignore the rest.

The issue I am having is in the do loop, I get continuous looping. In the replace, I get the roles but I also get the please remove groups line.

Upvotes: 0

Views: 65

Answers (2)

Lee_Dailey
Lee_Dailey

Reputation: 7489

[edit since the sample data changed so very much, the previous code won't work.]

what it does ...

  • fakes reading in a text file as a single multiline string
  • breaks that multiline string into blocks at the blank lines
  • iterates thru those blocks
  • splits the block on line ends
  • gets the type name from the 1st line
  • gets the items from the remaining lines and stores them in an array
  • builds a [PSCustomObject] that holds the type of target and the list of items
  • sends that out to the $Results collection
  • gets the items for one of the target types
    you can replace Roles with one of the other types - Groups is one such.
  • shows the whole $Results collection content
    that array can be neatly exported to a CSV if desired.

the code ...

# fake reading in a text file as one multiline string
#    in real life, use Get-Content -Raw
$InStuff = @'
Please remove the following Roles:
Role1
Role2

Please remove the following Groups:
Groups1
Groups2

Please remove the following Profiles:
Profiles1
Profiles3
Profiles8

Please remove the following DGroups:
DG1
DG9
DG12
'@

$Results = foreach ($Block in $InStuff -split "`r`n`r`n|`r`r|`n`n")
    {
    $SplitBlock = $Block -split "`r`n|`r|`n"
    $BlockName = $SplitBlock[0].Split(' ')[-1].Trim(':')
    $ItemList = $SplitBlock[1..$SplitBlock.GetUpperBound(0)]

    [PSCustomObject]@{
        TargetType = $BlockName
        TargetList = $ItemList
        }
    }

$Results.Where({$_.TargetType -eq 'Roles'}).TargetList
'=' * 30
$Results

output ...

TargetType TargetList
---------- ----------
Roles      {Role1, Role2}
Groups     {Groups1, Groups2}
Profiles   {Profiles1, Profiles3, Profiles8}
DGroups    {DG1, DG9, DG12}

Upvotes: 1

$file -replace '.+(?=Roles:|Groups:|Profiles:|DGroups:)'

Upvotes: 0

Related Questions