How to Use Get-Content in PowerShell: Simple Guide
Use
Get-Content in PowerShell to read the contents of a file line by line. Simply provide the file path as an argument, and it returns the file's text as output.Syntax
The basic syntax of Get-Content is simple. You specify the file path you want to read. You can also add options like -Encoding to control text encoding or -Tail to get the last lines.
Get-Content -Path <file-path>: Reads the whole file.-Encoding: Specifies the file encoding (e.g., UTF8, ASCII).-Tail <number>: Gets the last number of lines.
powershell
Get-Content -Path "C:\example\file.txt" Get-Content -Path "C:\example\file.txt" -Encoding UTF8 Get-Content -Path "C:\example\file.txt" -Tail 5
Example
This example reads a text file named sample.txt and prints its contents line by line. It shows how easy it is to get file content with Get-Content.
powershell
Get-Content -Path "sample.txt"Output
Line 1: Hello, world!
Line 2: This is a sample file.
Line 3: PowerShell makes reading files simple.
Common Pitfalls
One common mistake is using Get-Content on very large files without filtering, which can slow down your script. Another is forgetting to specify the correct file path or encoding, causing errors or wrong output.
Also, Get-Content reads files line by line by default, so if you want the entire content as a single string, you need to join the lines.
powershell
## Wrong: Reading large file without filter Get-Content -Path "largefile.txt" ## Right: Using -Tail to read last 10 lines Get-Content -Path "largefile.txt" -Tail 10 ## Wrong: Assuming output is a single string $content = Get-Content -Path "file.txt" Write-Output $content.Length # This shows number of lines, not characters ## Right: Joining lines into one string $content = (Get-Content -Path "file.txt") -join "`n" Write-Output $content.Length # Now shows total characters
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| -Path | Specifies the file path to read | Get-Content -Path "file.txt" |
| -Encoding | Sets the text encoding (UTF8, ASCII, etc.) | Get-Content -Path "file.txt" -Encoding UTF8 |
| -Tail | Gets the last N lines of the file | Get-Content -Path "file.txt" -Tail 5 |
| -Wait | Waits for new lines (like tail -f) | Get-Content -Path "log.txt" -Wait |
Key Takeaways
Use Get-Content with the file path to read file contents line by line.
Specify encoding with -Encoding to handle different text formats correctly.
Use -Tail to read only the last few lines of large files efficiently.
Join lines if you need the entire file content as a single string.
Avoid reading very large files without filters to keep scripts fast.