PowerShell Read File Contents

PowerShell offers a number of cmdlets for working with files. Sometimes we may need to retrieve the contents of file, to display it, or process it. PowerShell provides a number of different ways to access the contents of a file. Let’s say we have a file called text.txt in the current directory. The file contains the following:

1
2
3
4
5
This is line number 1
This is line number 2
This is line number 3
This is line number 4
This is line number 5

PowerShell provides the Get-Content cmdlet that can be used to obtain the contents of a file.

1
Get-Content .\text.txt

The above command will print the contents of the file.

1
2
3
4
5
This is line number 1
This is line number 2
This is line number 3
This is line number 4
This is line number 5

As we mentioned PowerShell provides a .net environment. We can use the System.IO.File class to obtain the file contents.

1
[System.IO.File]::ReadAllText(".\text.txt")

The above code calls the static method ReadAllText of the System.IO.File class, returning the file contents as a string.

We can also use the Get-Content cmdlet to access the first N number of lines from a file.

1
Get-Content .\text.txt  -totalcount 3

The above command will output the first three lines of the text file.

1
2
3
This is line number 1
This is line number 2
This is line number 3

We can also sort the contents of the file by using the Sort-Object cmdlet.

1
Get-Content .\text.txt  | Sort -Descending

The above command will sort the contents of the file in descending order.

1
2
3
4
5
This is line number 5
This is line number 4
This is line number 3
This is line number 2
This is line number 1

Conclusion

In this small tutorial we looked at how we can read the contents of a file in Powershell. We also looked at how we can sort the files contents.