Store Text File Contents in Variable Using PowerShell
Get-Contentto Store Entire Text File Contents in Variable in PowerShell
[IO.File]::ReadAllTextto 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,
This tutorial will teach you to store entire text file contents in the PowerShell variable.
Get-Content to Store Entire Text File Contents in Variable in PowerShell
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
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 = Get-Content C:\New\test.txt
The file content is stored as an array of newline-delimited strings by default.
To store entire text file contents in one string, you can use the
-Raw dynamic parameter.
$b = Get-Content C:\New\test.txt -Raw
[IO.File]::ReadAllText to Store Entire Text File Contents in Variable in PowerShell
[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
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