PowerShell Reading Files
Reading files is getting the text stored in a file back into a script. Get-Content reads a file and gives back its lines, one line at a time.
Read a one-line file
Create the file first, then read it. Get-Content prints the line it finds.
Set-Content -Path "fruit.txt" -Value "apple"
Get-Content -Path "fruit.txt"Count lines and pick one
Several lines come back as a list. Count gives the number of lines, and a position picks one line.
Set-Content -Path "fruit.txt" -Value @("apple", "banana", "cherry")
$lines = Get-Content -Path "fruit.txt"
$lines.Count
$lines[0]
$lines[-1]Filter the lines you read
Send the lines through a pipeline and keep only the ones you want. Here only lines longer than 5 letters are kept.
Set-Content -Path "fruit.txt" -Value @("apple", "banana", "cherry")
Get-Content -Path "fruit.txt" | Where-Object { $_.Length -gt 5 }Example
Set-Content -Path "fruit.txt" -Value @("cherry", "apple", "banana")
$lines = Get-Content -Path "fruit.txt"
$lines.Count
($lines | Sort-Object) -join ", "Key points
- Get-Content reads a file and gives back its lines.
- A file with one line gives back that single line of text.
- A file with several lines gives back a list of lines.
- Store the lines in a variable to count them or pick one by its position.
- Lines from Get-Content can be sent through a pipeline like any other values.
In this example, the file is created with three lines in mixed order. Get-Content reads them into a variable, Count prints how many lines there are, and Sort-Object puts them in order before they are joined into one line.
Note
Get-Content gives back the text of the file, not the file itself.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A file holds apple, banana, and cherry on three lines. What does (Get-Content -Path "fruit.txt").Count give?