Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call the properties/methods on the Piped Object

Tags:

powershell

I am trying to understand how to pipe | an object and call the properties or methods on that.

Ex:
$a = Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\
$a.GetSomething()  //calls the method
(Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\).GetSomething() //calls the method

Can I pipe the output of the Get-Item and invoke properties/methods on it?

Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\ | call GetSomething()
like image 940
RaceBase Avatar asked Aug 19 '16 08:08

RaceBase


People also ask

How do I get the properties of an object in PowerShell?

Object properties To get the properties of an object, use the Get-Member cmdlet. For example, to get the properties of a FileInfo object, use the Get-ChildItem cmdlet to get the FileInfo object that represents a file. Then, use a pipeline operator ( | ) to send the FileInfo object to Get-Member .

What are the some of the ways you can see the properties and methods available to a PowerShell command?

To display all the properties and methods available for the get-service cmdlet you need to pipeline Get-Member (alias gm). MemberType 'Property' is to display the specific property like machinename, servicename, etc.

What PowerShell command selects specific properties from an object?

The Select-Object cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array.


2 Answers

The short answer is no. You can't call a method like this using Pipeline. But you can surround your Get-Item invoke in parentheses and invoke it:

(Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\).GetSomething()

If you don't want that, you could abuse the Select-Object cmdlet:

Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\  | select { $_.GetSomething() }
like image 118
Martin Brandl Avatar answered Oct 17 '22 22:10

Martin Brandl


It's not possible without writing something to make it so. That something would be pretty confusing.

Like this.

filter Invoke-Method {
    param(
        [String]$Method,

        [Object[]]$ArgumentList
    )

    $_.GetType().InvokeMember(
        $Method.Trim(),
        ([System.Reflection.BindingFlags]'InvokeMethod'),
        $null,
        $_,
        $ArgumentList
   )
}
"qwerty" | Invoke-Method Replace 'q', 'z'

Properties are easier in that there's already a command to do that:

(...).GetSomething() | Select-Object Property1, Property2
like image 22
Chris Dent Avatar answered Oct 17 '22 23:10

Chris Dent