Function Powershell函数:管道和公共参数值之间的wierd差异
我对powershell处理函数参数的方式感到困惑 因此,我根据我的真实脚本制作了这个用于测试的ps模块示例:Function Powershell函数:管道和公共参数值之间的wierd差异,function,powershell,parameters,pipeline,Function,Powershell,Parameters,Pipeline,我对powershell处理函数参数的方式感到困惑 因此,我根据我的真实脚本制作了这个用于测试的ps模块示例: function test { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=
function test {
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [System.Management.Automation.PSObject]$InputObject
)
Begin {
}
Process {
Write-Host $InputObject
}
End {
}
}
Export-Modulemember -function test
将其另存为test.psm1&导入,并执行两项测试:
第一次测试:
(get-process | select -first 5) | test
将随此返回:
System.Diagnostics.Process (7zFM)
System.Diagnostics.Process (7zFM)
System.Diagnostics.Process (AcroRd32)
System.Diagnostics.Process (AcroRd32)
System.Diagnostics.Process (AESTSr64)
第二次测试:
test -InputObject (get-process | select -first 5)
将返回以下内容:
System.Diagnostics.Process (7zFM) System.Diagnostics.Process (7zFM) System.Diagn
ostics.Process (AcroRd32) System.Diagnostics.Process (AcroRd32) System.Diagnosti
cs.Process (AESTSr64)
当我使用变量存储和转发数据时也会发生同样的情况
powershell处理参数的方式似乎有所不同,我在使用-InputObject参数时返回的数据似乎以某种方式丢失了其数组格式
为什么会这样?有没有办法改变这种行为 Powershell管道会自动将数组和集合“展开”一级,并将它们一次一个地传递给下一个cmdlet或函数,因此当您通过管道发送该数组时,函数一次处理一个进程对象 使用该参数时,一次发送整个数组,函数处理的是数组对象,而不是进程对象,因此会得到不同的结果 试试这个,看看它是否对您的输出没有影响:
Process {
$InputObject | foreach {Write-Host $_ }
}
Powershell管道会自动将数组和集合“展开”一级,并将它们一次一个地传递给下一个cmdlet或函数,因此当您通过管道发送该数组时,您的函数一次只处理一个进程对象 使用该参数时,一次发送整个数组,函数处理的是数组对象,而不是进程对象,因此会得到不同的结果 试试这个,看看它是否对您的输出没有影响:
Process {
$InputObject | foreach {Write-Host $_ }
}