2012-11-18 29 views
6

我需要计算文本文件中的行数,并将其用作我的for循环的循环变量。问题是这样的:计算文件中的行数和存储变量

$lines = Get-Content -Path PostBackupCheck-Textfile.txt | Measure-Object -Line 

虽然这不会返回的行数,它的状态返回它无法相比,我的循环整数:

for ($i=0; $i -le $lines; $i++) 
    {Write-Host "Line"} 

回答

13

Measure-Object返回一个TextMeasureInfo对象,不是一个整数:

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 

要使用由0提供的信息该对象的属性:

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... 

该属性返回一个实际的整数

PS C:\> $lines.Lines.GetType() 

IsPublic IsSerial Name     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:\> _ 
4

对于它的价值,我发现上面的例子返回了错误的行数。我发现这个返回正确的计数:

$measure = Get-Content c:\yourfile.xyz | Measure-Object 
$lines = $measure.Count 
echo "line count is: ${lines}" 

你可能想测试两种方法来找出给你你想要的答案。使用“行”返回20和“计数”返回24.该文件包含24行。

+1

很显然'Lines'属性包含非空行数(即长度> 0的行)。虽然文档没有提到这一点。 –