Count lines in file and store in Variable
Measure-Object
returns a TextMeasureInfo
object, not an integer:
PS C:\> $lines = Get-Content .\foo.txt | Measure-Object -LinePS 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.TextMeasureInfoName 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.ValueTypePS C:\> $lines.Lines5
so you can use that in your loop:
PS C:\> for ($i = 0; $i -le $lines.Lines; $i++) { echo $i }012345PS 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.Countecho "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