mattnicola
mattnicola

Reputation: 403

Powershell: Return the second line of a Search only

I'm trying to return the result of the second line of a search I'm performing on a txt file. the data is in the format of

Readings       : \\Server1\memory\available mbytes :
                 2107

I want to get 2107 only. This is what I have so far:

$file = "D:\PerfTest.txt" # import data
$data = gc $file
$RAM = $Data | Select-String -Pattern "available mbytes :" | ForEach-Object -Context 1

but it gives me the following:

Readings       : \\Server1\memory\available mbytes :
                  2107

But I want to get the figure only. Any help please?

thanks

Just to add to the above, if I use

$RAM = $Data | Select-String -Pattern "available mbytes :" -Context 1 | Foreach {if ($_ -match '(\d+)$') {$matches[1]}}

it returns whole numbers and not decimals. so anything with a decimal come out 78125 instead of 0.78125

Upvotes: 2

Views: 2162

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

As already pointed out in the comments, -Context should be an argument to Select-String, not ForEach-Object.

The -Context parameter takes one or two integers to indicate how many lines before and after each match you want included.

In your case, you want 0 lines before and 1 line after, so the argument should be 0,1. Instead of loading the entire file into a variable, I would probably point Select-String directly to the file instead:

$RAM = Select-String -Path $file -Pattern "available mbytes :" -Context 0,1 | ForEach-Object {
    +$_.Context.PostContext[0].Trim()
}

The + will ensure that $RAM is an integer and not a string

Upvotes: 2

Related Questions