filjan
filjan

Reputation: 51

how can i get out numbers from a variable which contains a string? -power shell

So I have got a file which contains lines like this :

Peter Nagy 3 4 6 7 4

I need a Power shell script which asks the user to give a name, and it maths out the avarage of thoose numbers next to that name. Please help :)

$name1 = read-host 
$content = Get-Content test.txt
$talalt = $content | Where-Object { $_ -match  $name1 }

I have no idea what to do after this, and how to get out of thoose numbers from that string.

Thanks in advance

Upvotes: 0

Views: 128

Answers (2)

Keith Hill
Keith Hill

Reputation: 201592

You basically need to select from the first digit to the end of the line, split out the individual numbers and then average them e.g.:

$content | Where-Object { $_ -match  $name1 } | 
   Foreach {if ($_ -match '\D+(\d.*)') {-split $matches[1] | measure -average }}

Upvotes: 2

Arcass
Arcass

Reputation: 932

The following should do what you need:

$name1 = read-host 
$content = Get-Content NamesList.txt
$talalt = $content | Where-Object { $_ -match  $name1 }

$SplitString = $talalt.split(" ")

$NumberofNumbers = $SplitString.count-2

$total = 0;

for($i=2;$i-le $SplitString.count;$i++)
{
    $total = [int]$SplitString[$i] + $total
}

$average = $total/$NumberofNumbers

write-host "Average for $($name1) is $($average)"

regards Arcass

Upvotes: 2

Related Questions