Store Text File Contents in Variable Using PowerShell

Rohan Timalsina Jan 30, 2023 Apr 21, 2022
  1. Use Get-Content to Store Entire Text File Contents in Variable in PowerShell
  2. Use [IO.File]::ReadAllText to Store Entire Text File Contents in Variable in PowerShell
Store Text File Contents in Variable Using 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
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell File