【发布时间】:2021-06-04 13:48:45
【问题描述】:
我正在尝试了解 powershell 并将函数编写为 cmdlet,在其中一篇文章中找到了以下代码示例,但它似乎不想作为 cmdlet 工作,即使它有 [cmdletbinding()] 声明文件的顶部。
当我尝试做类似的事情时
1,2,3,4,5 | .\measure-data
它返回空响应(如果我在文件底部调用它并运行文件本身,该函数本身就可以正常工作)。
这是我正在使用的代码,任何帮助将不胜感激:)
Function Measure-Data {
<#
.Synopsis
Calculate the median and range from a collection of numbers
.Description
This command takes a collection of numeric values and calculates the
median and range. The result is written as an object to the pipeline.
.Example
PS C:\> 1,4,7,2 | measure-data
Median Range
------ -----
3 6
.Example
PS C:\> dir c:\scripts\*.ps1 | select -expand Length | measure-data
Median Range
------ -----
1843 178435
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[ValidateRange([int64]::MinValue,[int64]::MaxValue)]
[psobject]$InputObject
)
Begin {
#define an array to hold incoming data
Write-Verbose "Defining data array"
$Data=@()
} #close Begin
Process {
#add each incoming value to the $data array
Write-Verbose "Adding $inputobject"
$Data+=$InputObject
} #close process
End {
#take incoming data and sort it
Write-Verbose "Sorting data"
$sorted = $data | Sort-Object
#count how many elements in the array
$count = $data.Count
Write-Verbose "Counted $count elements"
#region calculate median
if ($sorted.count%2) {
<#
if the number of elements is odd, add one to the count
and divide by to get middle number. But arrays start
counting at 0 so subtract one
#>
Write-Verbose "processing odd number"
[int]$i = (($sorted.count+1)/2-1)
#get the corresponding element from the sorted array
$median = $sorted[$i]
}
else {
<#
if number of elements is even, find the average
of the two middle numbers
#>
Write-Verbose "processing even number"
$i = $sorted.count/2
#get the lower number
$x = $sorted[$i-1]
#get the upper number
$y = $sorted[-$i]
#average the two numbers to calculate the median
$median = ($x+$y)/2
} #else even
#endregion
#region calculate range
Write-Verbose "Calculating the range"
$range = $sorted[-1] - $sorted[0]
#endregion
#region write result
Write-Verbose "Median = $median"
Write-Verbose "Range = $range"
#define a hash table for the custom object
$hash = @{Median=$median;Range=$Range}
#write result object to pipeline
Write-Verbose "Writing result to the pipeline"
New-Object -TypeName PSobject -Property $hash
#endregion
} #close end
} #close measure-data
这是我从中获取代码的文章: https://mcpmag.com/articles/2013/10/15/blacksmith-part-4.aspx
编辑:也许我应该添加这篇文章前面部分的代码版本工作得很好,但是在添加了所有使它成为正确 cmdlet 的东西之后,比如帮助部分和详细行,这个东西就是不想工作,我相信缺少一些东西,我觉得这可能是因为它是为 powershell 3 编写的,我正在 win 10 ps 5-point 上测试它,但老实说,我什至不知道我在哪个方向应该寻找,所以才向你求助
【问题讨论】:
标签: powershell pipeline