【问题标题】:Powershell adding values togetherPowershell 将值加在一起
【发布时间】:2012-05-15 12:44:53
【问题描述】:

这是我的代码:

clear-host

function isNumeric ($x) {
try {
    0 + $x | Out-Null
    return $true
} catch {
    return $false
}
}

function output-file ($ave, $high, $low, $date)
{
write-output "Programer: Oday Sawaqed"
write-output "Class: CIS 124"
write-output "PowerShell Assignmnent"
write-output ""
Write-output ""
write-output " Current Date                    Average               Highest                        Lowest"
write-output " $date                $ave                   $high                 $low "
}


$array = @()
$hold
$n = 1

do {
$hold = read-host "number $n"
if (isNumeric $hold -eq $true){
if (999 -ne $hold) {
$array += $hold
$n = $n + 1
}
else
{
clear-host
write-host "Thank you."
write-host "The numbers you entered are:" $array
write-host "Please select a file name to save the output:"
$fileName = Read-host

$date = get-date -format "dddd, MMMM d, yyyy"
$array = $array | Sort-Object 
$ave = 
$high = $array | Select-Object -last 1
$low = $array | Select-Object -first 1

output-file $ave $high $low $date | Out-File c:\$fileName.txt
}
}
else {
write-host "Please enter a numeric value"
}
}
while (999 -ne $hold)

现在代码完美运行,我只是不知道如何将数组中的值相加来计算平均值。有人可以帮助我或给我一个提示! 我知道我需要将这些值相加然后除以 $n,我只是不知道如何添加这些值。

【问题讨论】:

    标签: arrays powershell add powershell-2.0


    【解决方案1】:

    要计算平均值,您可以使用Measure-Object Cmdlet:

    ($array | Measure-Object -Average).average
    

    【讨论】:

    • 非常感谢 :) 我知道你可以这样做,只是我被放置为 .ave 而不是 .average ,这就是为什么它从来没有工作过。我还是菜鸟。但是,是的,谢谢!
    • +1,我正在寻找如何对数组求和。你提醒我 measure-object 也可以完成许多数学类型的任务。
    【解决方案2】:

    我found 进行添加的一种方法是这样的:

    
    $sum = $array -join '+'
    Invoke-Expression $sum
    

    $sum 的输出只是简单地添加“+”,然后invoke-expression 实际上会为您计算。所以你的输出看起来像:

    
    $sum
    1+2+3+4+5+6+7+8+9
    Invoke-Expression $sum
    45
    

    【讨论】:

    • 链接中列出的第一个使用“measure-object”计算总和的方法怎么样?
    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 2018-03-07
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多