Lots of applications will output error logs and information in the form of a text file, so at some point you may find yourself needing to import data from a text file into Powershell.
Fortunately, there is an easy way to do so, with the Get-Content command.
First, let's create a list to import:
Google Bing Duckduckgo Yahoo
By storing this list as SearchEngines.txt, in the same folder as the script we're running, we can call this:
Get-Content -Path $PSScriptRoot\'SearchEngines.txt'
Get a specific number of lines
To get a specific number of lines, you can use the -TotalCount parameter.
For instance, to get the first 3 lines back, you can run the following:
Get-Content -Path $PSScriptRoot\'SearchEngines.txt' -TotalCount 3
Google Bing Duckduckgo
Get the lines at the end
To get the last lines of a file, we can use the -Tail parameter:
# Get the last two lines Get-Content -Path $PSScriptRoot\'SearchEngines.txt' -Tail 2
Get a specific line
To get a specific line, we can first filter down by -TotalCount, and get the last element.
How do we get the last element? Do we use -Tail?
# Try to get the 3rd line, by taking the first 3 elements, and getting the last Get-Content -Path $PSScriptRoot\'SearchEngines.txt' -TotalCount 3 -Tail 1
Get-Content : The parameters TotalCount and Tail cannot be used together. Please specify only one parameter.
To get the last element, we can wrap the query up in brackets, and get the -1th element in the array.
By doing so, it will find the element before the first, which wraps around to fetch the last element:
(Get-Content -Path $PSScriptRoot\'SearchEngines.txt' -TotalCount 3)[-1]