I need to count the number of lines in a text file and use this as my loop variable for my for
loop. Problem being this:
$lines = Get-Content -Path PostBackupCheck-Textfile.txt | Measure-Object -Line
Although this does return the number of lines, it returns it in a state that cannot be compared to an integer in my loop:
for ($i=0; $i -le $lines; $i++)
{Write-Host "Line"}
The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.
Using grep -c alone will count the number of lines that contain the matching word instead of the number of total matches. The -o option is what tells grep to output each match in a unique line and then wc -l tells wc to count the number of lines. This is how the total number of matching words is deduced.
Use the wc command to count the number of lines, words, and bytes in the files specified by the File parameter.
Measure-Object
returns a TextMeasureInfo
object, not an integer:
PS C:\> $lines = Get-Content .\foo.txt | Measure-Object -Line
PS C:\> $lines.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False TextMeasureInfo Microsoft.PowerShell.Commands.MeasureInfo
The information you want to use is provided by the Lines
property of that object:
PS C:\> $lines | Get-Member
TypeName: Microsoft.PowerShell.Commands.TextMeasureInfo
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Characters Property System.Nullable`1[[System.Int32, mscorlib, Vers...
Lines Property System.Nullable`1[[System.Int32, mscorlib, Vers...
Property Property System.String Property {get;set;}
Words Property System.Nullable`1[[System.Int32, mscorlib, Vers...
That property returns an actual integer:
PS C:\> $lines.Lines.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
PS C:\> $lines.Lines
5
so you can use that in your loop:
PS C:\> for ($i = 0; $i -le $lines.Lines; $i++) { echo $i }
0
1
2
3
4
5
PS C:\> _
For what it's worth, I found the above example returned the wrong number of lines. I found this returned the correct count:
$measure = Get-Content c:\yourfile.xyz | Measure-Object
$lines = $measure.Count
echo "line count is: ${lines}"
You probably want to test both methods to figure out what gives you the answer you want. Using "Line" returned 20 and "Count" returned 24. The file contained 24 lines.
$lines = Get-Content -Path PostBackupCheck-Textfile.txt | Measure-Object -Line | select -expand Lines
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With