简体   繁体   中英

How to easily create PSObject from function arguments to return result to pipeline?

Currently I'm doing like that:

function Invoke-Service
{
    Param(
        [parameter(Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)]
        [int] $Id,
        [parameter(Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)]
        [string] $Name,
        [parameter(Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)]
        [int] $Age
    )
    DoSomeWork |
        New-Object PSObject -Property @{ Id = $Id; Name = $Name; Age = $Age }
}

This function can obtain it's parameters directly or from Import-Csv output, or select output.

But very often I want to continue processing down the pipeline with all the power of PSObject :

Import-Csv -Path "data.csv" |
    Invoke-Service |
        ... #

And my question is: do I need to call New-Object enumerating all parameters or is there a keyword or other technique which I missed?

Use the $PSBoundParameters variable:

New-Object psobject -Property $PSBoundParameters

$PSBoundParameters is an automatic variable that contains a hashtable with an entry per named parameter, using the full parameter name as the key and the parameter argument as the value, so in your example it's already 100% aligned with the input you're trying to pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM