PowerShell offers powerful cmdlets for managing and Display Files with PowerShell, and among them, Cat (alias for Get-Content) and Get-Content are commonly used to read and display file contents. Though they may seem similar, understanding the differences between Cat and Get-Content can help you use them more effectively in your scripts and commands.
Understanding Get-Content
Get-Content is a versatile cmdlet that reads the contents of a file and outputs each line as an individual string. It’s useful for working with files line by line, as it returns an array of strings where each element corresponds to a line in the file.
In PowerShell, Cat is an alias for the Get-Content cmdlet. This alias comes from Unix-like systems, where the cat command is used to concatenate and display file contents. In PowerShell, Cat serves the same purpose but is simply a shorthand for Get-Content.
Apart from cat, there are other aliases for the Get-Content command, which you can find out by running the below command. As you can see below, gc and type are also aliases of Get-Command, along with cat.
Displaying the Contents of a File with PowerShell Cat
The primary usage of the PowerShell cat is showing a file’s contents on the screen. Running the cat command followed by the filename will tell the command to output the file’s contents for display. Run the below command to read the tmp.txt file and output the data on the screen
1 2 3 |
cat "C:\path\to\tmp.txt" |
Showing Lines from the Top & Bottom
Reading the first few lines of the file may help identify whether the file is what you need. PowerShell cat allows you to display a specific line or lines from a file to have a quick look as shown below.
1 2 3 |
cat tmp.txt -TotalCount 6 |
To View the contents from the bottom by specifying the -Tail parameter or its alias, which is -Last. This method is typical when troubleshooting with log files.
1 2 3 |
cat tmp.txt -Tail 5 |
Merging Contents Into a New File
Instead of simply showing the content on the screen, you can redirect the standard out of a command to a new file in PowerShell. Moreover, the PowerShell cat can read multiple files at once, which makes merging contents possible. Run the cat command to concatenate File1.txt and File2.txt as follows. The output redirect (>) sends the command output to the new file called catMerge.txt.
Method 1:
1 2 3 |
cat File1.txt,File2.txt > catMerge.txt |
Method 2:
1 2 3 |
cat File1.txt,File2.txt | Out-File Merge1.txt |
Appending the Contents of One File to Another
Another thing you can do with the Linux cat command is appending the contents of one file to another instead of overwriting the file or creating a new one.
1 2 3 4 |
# PowerShell cat with Add-Content cat File1.txt | Add-Content File2.txt |
This commands appends the contents of File1.txt to File2.txt.
1 2 3 4 |
# PowerShell cat with double redirection symbol (append) cat File1.txt >> File2.txt |
Leave A Comment