PowerShell offers a number of different ways to manage the variety of text files. Here we learn how to retrieve text from text files and how to find text in text files, all through PowerShell cmdlets.

How To Retrieve Text From Text Files

You can use the powershell Get-Content cmdlet which is used to retrieve all text from a text file specified by the Path parameter.

Executing the above cmdlet, You’ll see that the result was the entire contents of TestFile.txt. If you just wanted to see a particular line number? By default, Get-Content reads all the line in a text file and creates an array as its output with each line of the text as an element in that array.In this case, the array index number is equal to the text file line number. So we can get the each line of the txt file by using the array index number.

OUTPUT:

In the above example, the result of Get-Content is a type of System.Array and that by using index numbers in brackets you can get the value of text file. The index is start from Zero.

How To Find Text In Text Files

There are a many different ways to do this but the we can use Where-Object cmdlet which will be the easilest way. The Where-Object cmdlet is a popular cmdlet that allows you to “filter out” various information from the output of other cmdlets. When using Where-Object we must use the $_ variable and this is a special variable in PowerShell known as the pipeline variable.

OUTPUT:

From the above script, the Where cmdlet find the lines which contain the text “test” from the txt file (found 2 matches) and gives as output.