powershell管道物件到函數

powershell管道物件到函數

這是我想做的事情的存根:

function Set-test {
[CmdletBinding()]
    param(
        [Parameter(Mandatory=$True,
               ValueFromPipeline=$True)]
        [object[]]$inputObject
    )
    Write-Verbose "Set-test: input obj= $inputObject" 

    PROCESS {
        foreach ($obj in $inputobject) {
            Write-Output $obj
        }
    }   
}

function Get-test {
    $obj = New-Object PSObject
    $obj | Add-Member -MemberType NoteProperty -Name "swName" -Value "banana"
    $obj | Add-Member -MemberType NoteProperty -Name "Version" -Value "3.2.2"
    Write-Output "obj = $obj"
    $obj | Set-test -verbose    
}

這是輸出:

PS > Get-test
obj = @{swName=banana; Version=3.2.2}
VERBOSE: Set-test: input obj= 
Get-Process : Cannot evaluate parameter 'Name' because its argument is  specified as a script block and there is no input. A script block cannot be evaluated without input.
At C:\Users\username\Documents\WindowsPowerShell\Modules\mytool\mytools.psm1:204 char:13
+     PROCESS {
+             ~
+ CategoryInfo          : MetadataError: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.GetProcessCommand

從詳細輸出中可以看出,該物件似乎沒有通過管道傳輸到該函數,這讓我感到困惑。

答案1

您不能在 begin{}、process{} 或 end{} 區塊之外的 set-test 中使用該寫入詳細資訊。它把事情搞砸了。如果將其移動到 process{} 區塊內,它就可以正常工作。

相關內容