Get values (in pairs) from a text file

Goodmorning everyone.
I need help from you if possible.
I have a file with this structure that I have to process with PowerShell.

some lines of text
ID: abc
some lines of text
ROLE: manager
some lines of text
ID: def
some lines of text
ROLE: editor
some lines of text

I need to get the values of ID and ROLE … let’s say in pairs
because subsequently I will have to use these two values (ID and ROLE) in this way
C:\COMMAND abc manager
C:\COMMAND def editor

I hope I explained myself well … but I’m afraid not!
Thank you all

 

Ciao
Andrea

Hi There,

Not sure we can do it in a definite way, but hope the below will help you with your requirement…

$Data = Get-Content -Path C:\Temp\Test.txt
$FilteredData = $Data | Select-String -Pattern 'ID|Role'

$Res = @{ID = ''; ROLE = '' }
$Out = @()
$i = 0

While ($i -lt $FilteredData.Count)
{
    $Res.ID = ($FilteredData[$i]).ToString().Split(":")[-1].Trim()
    $Res.ROLE = ($FilteredData[$i + 1]).ToString().Split(":")[-1].Trim()
    $Out += $Res
    $i += 2
}

$Out

Thank you.

Andrea,

here is a great video about text parsing with Powershell: Sophisitcated Techniques of Plain Text Parsing.

Dear Kiran, many thanks for your code! You have been very kind.
I did a test … Unfortunately something is not working.

The while loop does not seem to progress correctly. The ID and ROLE values always remain the same.
Name Value


ID ghi
ROLE manager
ID ghi
ROLE manager
ID ghi
ROLE manager

The file is
ID: abc
ROLE: manager
ID: def
ROLE: editor
ID: ghi
ROLE: manager

Do you have an idea? If I don’t disturb you too obviously.
I don’t want to take advantage of your availability
Thank you
Hello
Andrew

Thank you very much Olaf.
I am a little (a lot!) in difficulty with the English language but as soon as I have time I will definitely watch the video linked by you.
Thank you and good day
Andrew

Yeah weird, not sure why it is behaving odd.
As state in the video which @Olaf shared, there are various methods which we can convert non-structured data into PowerShell objects, so it all depends on the data what you have. However try the code below, hope it works.
$Data = Get-Content -Path C:\Windows\Temp\Test.txt
$FilteredData = $Data | Select-String -Pattern 'ID|Role'

$i = 0

$Output = While ($i -lt $FilteredData.Count)
{
New-Object -TypeName psobject -ArgumentList @{
ID = ($FilteredData[$i]).ToString().Split(“:”)[-1].Trim()
ROLE = ($FilteredData[$i + 1]).ToString().Split(“:”)[-1].Trim()
}
$i += 2
}

$Output

Thank you.

Kiran,
sorry for the delay in my reply. I had some problems.
I tried your code and it worked fine :smiley: !!!
You were really nice to waste time helping a stranger!
I hope one day to return the favor.

Have a nice day :smiley:
Thank you