0
0
PowershellHow-ToBeginner · 3 min read

How to Read a File in PowerShell: Simple Commands and Examples

To read a file in PowerShell, use the Get-Content cmdlet followed by the file path, like Get-Content 'path\to\file.txt'. This command outputs the file content line by line to the console.
📐

Syntax

The basic syntax to read a file in PowerShell is:

  • Get-Content <FilePath>: Reads the content of the file at the specified path.
  • <FilePath>: The full or relative path to the file you want to read.

This command outputs the file content as an array of lines.

powershell
Get-Content <FilePath>
💻

Example

This example reads the content of a file named example.txt located in the current directory and prints it line by line.

powershell
Get-Content 'example.txt'
Output
This is line 1 of the file. This is line 2 of the file. This is line 3 of the file.
⚠️

Common Pitfalls

Common mistakes when reading files in PowerShell include:

  • Using incorrect file paths or forgetting to escape backslashes in Windows paths.
  • Trying to read very large files without considering memory usage.
  • Confusing Get-Content with commands that read binary files (it reads text files by default).

Always verify the file path and use quotes around paths with spaces.

powershell
## Wrong way (missing quotes and wrong path)
Get-Content C:\Users\User\Documents\file.txt

## Right way (quotes and escaped backslashes)
Get-Content 'C:\Users\User\Documents\file.txt'
📊

Quick Reference

CommandDescription
Get-Content Reads the content of a text file line by line.
Get-Content -Raw Reads the entire file content as a single string.
Get-Content -Tail Reads the last lines of the file.
Get-Content -Head Reads the first lines of the file.

Key Takeaways

Use Get-Content followed by the file path to read a file in PowerShell.
Always enclose file paths in quotes, especially if they contain spaces.
Get-Content outputs file content line by line by default.
Use the -Raw parameter to read the entire file as one string.
Check file paths carefully to avoid errors when reading files.