0
0
PowerShellscripting~5 mins

Reading file content (Get-Content) in PowerShell

Choose your learning style9 modes available
Introduction
You use Get-Content to read what is inside a file. It helps you see or use the file's text in your script.
You want to check the text inside a log file to find errors.
You need to read a configuration file to get settings for your script.
You want to display the contents of a text file on the screen.
You want to process each line of a file one by one in your script.
Syntax
PowerShell
Get-Content -Path <file-path> [-Encoding <encoding>] [-TotalCount <number>] [-Tail <number>]
Replace with the path to your file, like 'C:\temp\file.txt'.
You can use -Tail to get only the last few lines of the file.
Examples
Reads all lines from the file 'notes.txt' and shows them.
PowerShell
Get-Content -Path 'C:\temp\notes.txt'
Shows only the last 5 lines of 'log.txt'.
PowerShell
Get-Content -Path 'C:\temp\log.txt' -Tail 5
Reads the file 'data.csv' using UTF8 encoding.
PowerShell
Get-Content -Path 'C:\temp\data.csv' -Encoding UTF8
Sample Program
This script creates a file named 'sample.txt' with three lines. Then it reads the file using Get-Content and prints each line with a message.
PowerShell
Write-Output "Reading file content example"

# Create a sample file
"Line 1`nLine 2`nLine 3" | Out-File -FilePath "sample.txt" -Encoding UTF8

# Read the file content
$content = Get-Content -Path "sample.txt"

# Show the content
foreach ($line in $content) {
    Write-Output "Read line: $line"
}
OutputSuccess
Important Notes
Get-Content reads the file line by line and returns an array of lines.
If the file is large, reading all lines at once may take time.
Use -Tail to read only the last few lines quickly.
Summary
Get-Content reads text from files line by line.
You can read the whole file or just parts like the last lines.
It is useful to see or use file contents in your scripts.