Store Text File Contents in Variable Using PowerShell
-
Use
Get-Content
to Store Entire Text File Contents in Variable in PowerShell -
Use
[IO.File]::ReadAllText
to Store Entire Text File Contents in Variable in PowerShell

PowerShell supports different file tasks, such as create, copy, move, delete, rename, and read a file. You can read a text file and view its content on the console.
Variables are denoted by text strings and begin with the dollar $
sign. For example, $a
, $b
, $data
, etc.
This tutorial will teach you to store entire text file contents in the PowerShell variable.
Use Get-Content
to Store Entire Text File Contents in Variable in PowerShell
The Get-Content
cmdlet gets the item’s content at the specified location. You can use this command to view the text in a file or the content of a function.
The following command gets the content of a file C:\New\test.txt
.
Command:
Get-Content C:\New\test.txt
Output:
This is a first line.
This is a second line.
This is a third line.
The following examples store the content of a text file test.txt
in variable $a
.
$a = Get-Content C:\New\test.txt
The file content is stored as an array of newline-delimited strings by default.
$a.Count
Output:
3
To store entire text file contents in one string, you can use the -Raw
dynamic parameter.
$b = Get-Content C:\New\test.txt -Raw
$b.Count
Output:
1
Use [IO.File]::ReadAllText
to Store Entire Text File Contents in Variable in PowerShell
The [IO.File]::ReadAllText
is a .NET framework class that reads the content of a text file. It returns the entire text file content in one string.
$c =[IO.File]::ReadAllText('C:\New\test.txt')
$c.Count
Output:
1
Related Article - PowerShell File
- Find a Specific File by Name Using PowerShell
- PowerShell Loop Through Files and Folders
- PowerShell Copy File and Rename
- Split Large File in PowerShell
- Read CSV File Line by Line in PowerShell
- Unblock Files Using PowerShell