Measure-Object - 平均四舍五入到小数点后两位

Measure-Object -Average round to two decimal places

这可能就像分离出不使用多个管道的语句一样简单,但是,我有以下代码输入一个文本文件,其中包含从 0.0 到 11.0 的不同(通常 ~800)行数字或更多的。使用 Powershell,我想获取所有这些值并取平均值,四舍五入到小数点后两位。下面是尝试使用 Measure-Object -Average 的代码,但我知道这不是最佳选择,因为它输出的信息包括 Count、Max 和 Min,而我想要的只是平均值,没有其他 txt。

Get-Content C:\daily_values_uv_temp2_non_avg.txt | Measure-Object -Average | Out-File C:\daily_values_uv.txt

Get-Content returns 个字符串。如果你想计算数字的平均值,你需要先转换它......像这样:

Get-Content -Path C:\daily_values_uv_temp2_non_avg.txt |
    ForEach-Object{[float]$_} |
        Measure-Object -Average |
            Select-Object -Property Average -OutVariable result
[MATH]::Round($result.average,2)

要将结果四舍五入到小数点后两位,您可以使用 [MATH] class.

Round() 方法

马蒂亚斯是对的……我不知道。谢谢。

所以您实际上只需要将 Select-Object 添加到 select 之后的 属性。

Get-Content C:\daily_values_uv_temp2_non_avg.txt | 
    Measure-Object -Average | 
        Select-Object -ExpandProperty Average |
            Out-File C:\daily_values_uv.txt