PowerShell : Finding number of lines in a File

Requirement:

In Automation using PowerShell Scripting its very often a requirement to read input from a file.  Usually the input is separated by new line in the file. Your PowerShell should read all lines from the file and process the input line by line. Say, you have list of servers in file and you want to check service status for each of the server in the file. 

Solution:

In PowerShell Get-Content is used for most cases to read a file and process it line by line. It just works fine in most of the cases. But if you need to implement reporting number of lines processed there comes a special case with Get-Content usage. Get-Content returns number of Characters in line instead of number of lines, If there is only One line in the file.

You can alternatively use Get-Content + Count property  OR Get-Content + Measure-Object + Lines property to handle files with only one line of input.

Example:

PowerShell Script and Execution output in PowerGUI.

image

Code:

$Servers           = Get-Content "C:\Temp\Servers.txt" 

#Method#0 If there is only One line in the file, this method returns number of Characters in line instead of number of lines. 
$TotalServersCount = ($Servers).Length 
Write-Output "Number of Servers Using Get-Content + Length property is: $TotalServersCount"

#Method#1
$TotalServersCount = ($Servers).Count 
Write-Output "Number of Servers Using Get-Content + Count property is : $TotalServersCount"

#Method#2
$TotalServersCount = Get-Content "C:\Temp\Servers.txt" | Measure-Object –ine
$TotalServersCount = $TotalServersCount.Lines
Write-Output "Number of Servers Using Get-Content + Measure-Object + Lines property is: $TotalServersCount"

Execution:

PS C:\> type C:\Temp\Servers.txt
USSRV01
PS C:\> C:\temp\Read-Number-Of-Lines-Ina-File.ps1
Number of Servers Using Get-Content + Length property is: 7
Number of Servers Using Get-Content + Count property is : 1
Number of Servers Using Get-Content + Measure-Object + Lines property is: 1
PS C:\>

 

References:

Script file:

Leave a Reply

Your email address will not be published. Required fields are marked *