【问题标题】:Powershell scripting methodargumentconversioninvalidargumentPowershell脚本方法argumentconversioninvalidargument
【发布时间】:2016-03-09 11:34:13
【问题描述】:

我是 Powershell 脚本的新手,我想找到结果变量中数字的标准差。

以下是我的代码:

param(

    ## The command to measure
    [Scriptblock] $Scriptblock,

    ## The number of times to measure the command's performance
    [int] $Iterations = 2
)

Set-StrictMode -Version Latest

## Figure out how many extra iterations we need to account for the outliers
$buffer = [int] ($iterations * 0.1)
$totalIterations = $iterations + (2 * $buffer)

## Get the results
$results = 1..$totalIterations |
    Foreach-Object { Measure-Command $scriptblock }

## Sort the results, and skip the outliers
$middleResults = $results | Sort TotalMilliseconds |
    Select -Skip $buffer -First $iterations

$popdev = 0            

## Show the average
$avg = $results | Measure-Object -Average | select Count, Average    
$middleResults | Measure-Object -Average TotalMilliseconds  
foreach ($number in $results){            
  $popdev +=  [math]::pow(($number - $avg.Average), 2)            
} 

我收到以下错误:

计数:2 平均:351.1846 总和: 最大 : 最低限度 : 属性:TotalMilliseconds

无法将参数“1”,值为:“”,将“op_Subtraction”转换为类型“System.TimeSpan”:“无法将 null 转换为 键入“System.TimeSpan”。” 在 C:\script.ps1:55 char:3 + $popdev += [数学]::pow(($number - $avg.Average), 2) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我看到的第一个问题(这是错误的来源)是 $results 是 Timespan 对象的集合(因为这是 measure-command 输出的内容)。

    其次,您在处理$middleresults 时没有指定要平均的属性。

    第三,您没有将以$middleresults 开头的管道分配给任何东西,所以它只是输出。我不确定你想对这个结果做什么。

    因为$results 是Timespan 对象,所以在pow 函数内,当您单独使用$number 时,减去平均值时会出错。如果你使用$number.TotalMilliseconds,我想你会得到你所期望的。

    【讨论】:

    • 感谢添加 "$number.TotalMilliseconds" 效果很好,还更改了这一行 "$avg = $results | Measure-Object -Average TotalMilliseconds | select Count, Average " 我想得到平均值和标准差对于 $results
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2022-01-23
    • 2020-12-05
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多