How to Read a File using PowerShell

If you are working as an admin on Windows Core Server and want to check the contents of a file, you can execute the following command:

get-content C:\testfile.txt

This command will display the contents of theĀ file using PowerShell. To save the contents in a variable, you can execute:

$FileContent = get-content C:\testfile.txt

To read the first few lines (I suppose the first five lines of the file here) you can use a for-each loop statement.

$filecontent = Get-Content info.txt
for( $i=0; $i -lt 5; $i++ )
 {
  Write-Host $filecontent[$i]
 }

The above script loops through the first 5 lines of the file that we loaded via Get-Content commands and prints them on the terminal.

Leave a Comment