Search code examples
powershellpiping

Piping into objects/properties/methods in PowerShell


In PowerShell, you can pipe into Cmdlets and into scripted functions. But is it possible to pipe into objects, properties, or member functions?

For example, if I have a database connection object $dbCon, I want to be able to so something like this:

$dbCon.GetSomeRecords() | <code-to-manipulate-those-records | $dbCon.WriteBackRecords()

I know the same functionality can be achieved with Foreach-Object or with a Cmdlet that gets the object as an argument - the reason I want to pipe directly to the object or to it's members is to achieve elegance and to keep the OOP style(using an object's method instead of sending the object as an argument)

Is it possible?


EDIT:

It looks like people don't understand my question, so I need to clarify it:

PowerShell can pipe to normal functions. I can Write:

function ScriptedFunction
{
    $input|foreach{"Got "+$_}
}
1,2,3|ScriptedFunction

And get
Got 1
Got 2
Got 3

As the result. But when I try to use that technique with a scripted method:

$object=New-Object System.Object
$object|Add-Member -MemberType ScriptMethod -Name ScriptedMethod -Value {$input|foreach{"Got "+$_}}
1,2,3|$object.ScriptedMethod

I get an error message: Expressions are only allowed as the first element of a pipeline.(adding () does not help BTW). What I'm looking for is a way to make that command work the same way it works with global functions.


Solution

  • This is not exactly what you are asking for but this has almost the same syntax: use a NoteProperty instead of a ScriptedMethod and call it using operators . or &:

    $object = New-Object System.Object
    $object | Add-Member -MemberType NoteProperty -Name Script -Value {$input|foreach{"Got "+$_}}
    1,2,3 | & $object.Script
    

    Output

    Got 1
    Got 2
    Got 3
    

    BUT: There is a caveat, perhaps a show stopper: this is not a script method at all, there will be no $this defined by the core for it (you can define $this = $object before invocation yourself but this is rather ugly, to send $object as a parameter would be better).