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.
1 |
Get-content -Path "C:\dotnet-helpers\BLOG\TestFile.txt" |
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.
1 2 3 4 |
$TxtContent = Get-content -Path "C:\dotnet-helpers\BLOG\TestFile.txt" $TxtContent.GetType() $TxtContent[0] $TxtContent[2] |
OUTPUT:
1 2 3 4 5 6 |
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array This is test text file Thanks for reading this posts. |
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.
1 |
Get-content -Path "C:\dotnet-helpers\BLOG\testfile.txt" | Where-Object {$_ -like '*test*'} |
OUTPUT:
1 2 |
This is test text file Will test this file by using Get-Content cmdlet |
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.
Leave A Comment