Difficulty with a extracting responses from text file in Powershell

Viewed 48

I am having a difficult time with finding and separating certain regular expressions in Powershell. I have an example of the following contents of the text file that I need to search in the link below. Beneath each question is the response.

Example of text file

I need to find the response to each question and just store it in an excel file. It is possible that the questions might be in a different order in the text file so I need to be able to extract the correct responses to their respective questions.

I can extract the questions by doing

$question1 = $file | Where-Object { $_.Contains("Name") }
$question2 = $file | Where-Object { $_.Contains("Are you feeling ok?") }
$question3 = $file | Where-Object { $_.Contains("Did you do your homework?") }
$question4 = $file | Where-Object { $_.Contains("List your favourite subjects?") }

I am having difficulty with extracting the response right underneath it (because the questions could be in any order. In the future there could be more questions in the text file).

1 Answers

Assuming a text file exaclty as you mention:

* Name
  Jeff

* Are you feeling ok?
  Yes

* Did you do your homework?
  No

* What are your favourite subjects?
  Maths, science

Then you could use Select-String to get the questions and answers like this:


Get-Content -Path .\test.txt |
    Select-String -Pattern '^\* .*$' -Context 1 |
        ForEach-Object {
            [PsCustomObject]@{
                Question = $_.Line -replace '\* ', '' 
                Answer   = $_.Context.PostContext[0].Trim()
            }
        }

Example output:

Question                          Answer        
--------                          ------        
Name                              Jeff          
Are you feeling ok?               Yes           
Did you do your homework?         No            
What are your favourite subjects? Maths, science

The order of the questions in the file doesn't matter, though they will appear in the output in the order they are found. You can use Export-Csv to create a CSV file, which can be opened in Excel, or look on-line for technique of manipulating XLSX files from PowerShell.

Related