2010-04-06 70 views

回答

20

您还可以使用readcount属性排除线路:

get-content d:\testfile.txt | where {$_.readcount -lt 3 -or $_.readcount -gt 7} 
7

如果我需要只选择一些行,我会直接索引到数组:

$x = gc c:\test.txt 
$x[(0..2) + (8..($x.Length-1))] 

也可以创建一个功能Skip-Objects

function Skip-Object { 
    param(
     [Parameter(Mandatory=$true,ValueFromPipeline=$true)][PsObject]$InputObject, 
     [Parameter(Mandatory=$true)][int]$From, 
     [Parameter(Mandatory=$true)][int]$To 
    ) 

    begin { 
     $i = -1 
    } 
    process { 
     $i++ 
     if ($i -lt $from -or $i -gt $to) { 
      $InputObject 
     } 
    } 
} 

1..6 | skip-object -from 1 -to 2 #returns 1,4,5,6 
'a','b','c','d','e' | skip-object -from 1 -to 2 #returns a, d, e 
4

PowerShell Community Extensions带有一个跳过-Object cmdlet:

PS> 0..10 | Skip-Object -Index (3..7) 
0 
1 
2 
8 
9 
10 

请注意,Index参数ter是基于0的。

2

同样,如果没有扩展(注意,-skip需要的项目数跳过,而不是指数)

$content = get-content d:\testfile.txt 
($content | select -first 3), ($content | select -skip 8)