计算文件中的行数并存储在变量中 [英] Count lines in file and store in Variable
问题描述
我需要计算文本文件中的行数,并将其作为循环变量用于 for
循环。问题是:
$ lines = Get-Content -Path PostBackupCheck-Textfile.txt | Measure-Object -Line
虽然这会返回行数,但它返回的状态是($ i = 0; $ i -le $ lines; $ i ++)不能与我的循环中的整数进行比较:
)
{Write-HostLine}
<
$ b> Measure-Object
返回一个 TextMeasureInfo
对象,
$ b
PS C:\> $ lines = Get-Content。\foo.txt |测量对象线 -
PS C:\> $ lines.GetType()
IsPublic IsSerial名称BaseType
-------- -------- ---- --------
True False TextMeasureInfo Microsoft.PowerShell.Commands.MeasureInfo
您要使用的信息是由该对象的 Lines
属性提供:
PS C:\> $ lines | Get-Member
类型名称:Microsoft.PowerShell.Commands.TextMeasureInfo
名称MemberType定义
---- ------- --- ----------
等式方法bool Equals(System.Object obj)
GetHashCode方法int GetHashCode()
GetType方法类型GetType()
ToString方法字符串ToString()
字符属性System.Nullable`1 [[System.Int32,mscorlib,Vers ...
Lines属性System.Nullable`1 [[System.Int32,mscorlib,Vers ...
Property Property System.String Property {get; set;}
Words属性System.Nullable`1 [[System.Int32,mscorlib,Vers ...
$ c
$ b 该属性返回一个实际的整数:
PS C:\> $ lines.Lines.GetType()
IsPublic IsSerial名称BaseType
-------- -------- ---- ------ -
True True Int32 System.ValueType
PS C:\> $ lines.Lines
5
所以你可以在循环中使用它:
PS C:\> for($ i = 0; $ i -le $ lines.Lines; $ i ++){echo $ i}
0
1
2
3
4
5
PS C:\> _
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"}
解决方案 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:\> _
这篇关于计算文件中的行数并存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!