Pergunta

I have the below code running in Powershell which searches for the string London, and works well thanks to some earlier assistance:

$sr = new-object System.io.streamreader(get-item C:\Temp\a.txt)
while ($line = $sr.readline()){ 
    if ($line -match "London"){ 
        $line} 
    }
}

However can anyone suggest a simple way to limit results so if a 100 matches are found I can choose to output only 1 result to file (or choose the quantity of lines that are output)

Thanks in advance

Foi útil?

Solução

You could add a loop constraint to your if statement. For example:

$sr = New-Object System.IO.StreamReader(Get-Item C:\Temp\a.txt)
$limit = 3; $i = 0
while ($line = $sr.ReadLine()) {   
    if ($line -match "London" -and $i -lt $limit) {
            $line
            $i += 1
    }
}

would limit the number of lines returned containing "London" to whatever you set the $limit variable to (in this case, up to the three first line matches found would be returned).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top