0

所以我有一个文件,其中包含这样的行:

Peter Nagy 3 4 6 7 4

我需要一个 Power shell 脚本,它要求用户提供一个名称,它会计算出该名称旁边的这些数字的平均值。请帮忙 :)

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

我不知道在此之后该怎么做,以及如何从该字符串中摆脱那些数字。

提前致谢

4

2 回答 2

2

以下应该做你需要的:

$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)"

关于阿卡斯

于 2012-12-06T16:05:16.477 回答
2

您基本上需要从第一个数字到行尾进行选择,将各个数字分开,然后对它们进行平均,例如:

$content | Where-Object { $_ -match  $name1 } | 
   Foreach {if ($_ -match '\D+(\d.*)') {-split $matches[1] | measure -average }}
于 2012-12-06T16:08:32.417 回答