Get-Content Cmdlet – What you Should Know

Author by Christopher Mank

If you're someone who spends at least a minimum amount of time using PowerShell, you've almost certainly run into the Get-Content cmdlet.  This cmdlet allows you to get the contents of a given file and there is plenty of documentation on the web on how to use it (Here, here and here). As the documentation states in two of the above links: Get-Content automatically creates an array based on the content it is retrieving; in the case of a text file, each line in the file will be a single item in the array. So after a simple test, this information was proved correct.  I simply created a text file like the one below. Test Get-Content File Image Then, I ran some commands to confirm that indeed, the output was of type array and that using array notation "[n]", you can pull any line from the file. PowerShell Get-Content Example Image But here is where our tale takes an interesting turn.  After working on a script, I started to see inconsistent results with this.  Take a look at this output. PowerShell Get-Content Example One Line Image As you can see from the above screenshot, instead of pulling a data type of array it is pulling a data type of string.  Even more, look at how the array notation functions.  Instead of pulling each line, it is pulling each character.  So what is going on here? As it turns out, if the file you pass to the Get-Content cmdlet only contains one line, instead of the output being of type array, the output is actually of type string.  So when one uses the array notation, just like in any other string, it pulls back characters not the lines. Test Get-Content File One Line Image In the case of my script, I simply added an IF statement when the total # of lines < 2 (Measure-Object -line).  I hope this helps those running into this caveat about the Get-Content cmdlet. Until the Whole World Hears, Christopher


Christopher Mank

Systems Architect