
Here, the $_ is a pipeline variable that represents the current line from the contents that come from Get-Content.īesides Where-Object, you can also use match and regex operators to find the exact text you want.
#POWERSHELL GET FILE DETAILS CODE#
The above code will output those lines that have the word “error” in them.

$stream_reader = New-Object System.IO.StreamReader This will display the second line, and so on. For example, if you want to read the first line, you can simply say:Īnd this will display the first line for you. This means you can pick out specific lines using the array index. If you print the type of this variable, you can see that it an array. In the above example, we used a variable for reading all the content. The Get-Content function reads every line in the text and stores them as an array, where each line is an array element. When you want to read the file to understand its contents, you’d have to do so one line at a time and the good news is, this is possible with PowerShell. Likewise, we can read the last few lines too: $file_data = Get-Content C:\logs\log01012020.txt You can display the contents of this variable or use it for more processing. Similar to a SQL query, you can choose the lines you want to read and the code for that is: $file_data = Get-Content C:\logs\log01012020.txtĪs the code suggests, the first 10 lines of the content will be stored in the variable and not the entire content. Many times, you may only have to read a certain part of a file to get the information you want. You can now use this variable $file_data for parsing or further processing. You can also move all the content to a variable and use that variable for further processing if that’s something that you want your code to do. When you execute this command, the contents of this file will be displayed in your command prompt or the PowerShell ISE screen, depending on where you execute it.

Here is the code that allows you to do this: When you want to read the entire contents of a text file, the easiest way is to use the built-in Get-Content function. In this article, we’ll see how you can read a text file in PowerShell. PowerShell understands this importance of text files and makes it easy to retrieve text and read from them easily.

This flexibility has also made text files the most convenient way to define scripts, store configuration details, and more. In fact, as an IT professional, you will have to create, read, or work with text files more often than you may think because text files come in a wide range of formats. Text files are ubiquitous and you’ll have to read through them, regardless of your role or job responsibilities.
