Ansgar Wiechers has provided the crucial pointer in a comment on Martin Brandl's answer:
The canonical way would be ForEach-Object
. It can be written pretty concisely using the alias %
:
... | % { $_.GetSomething() }
In PowerShell version 3 or higher, you an make the call even more concise with simplified syntax, which obviates the need for enclosing the call in { ... }
, having to explicitly refer to $_
, and needing to use parentheses ((...)
):
... | % GetSomething # short for: ... | ForEach-Object GetSomething
Note that if the method takes arguments, they must be supplied as an array (,
-separated), but without enclosing them in (...)
, because syntactically the arguments are being passed in argument mode, which also makes quoting simple string values optional - see examples below.
Examples:
Method call without arguments:
# Perform the equivalent of:
# (Get-Item Registry::HKLM\SOFTWARE\Classes\txtfile).GetValueNames()
# That is, get the names of the values defined on registry key
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\txtfile
PS> Get-Item Registry::HKLM\SOFTWARE\Classes\txtfile | % GetValueNames
EditFlags
FriendlyTypeName
Method call with one argument:
# Perform the equivalent of (Get-Date).ToString('u'); i.e.,
# get a date's universally sortable string representation.
PS> Get-Date | % ToString u # "u" may be quoted, but doesn't need to be.
2019-04-19 08:22:22Z
Method call with multiple arguments:
# Perform the equivalent of 'foo'.Replace('f', 'F'); i.e.,
# replace all lowercase Fs with uppercase ones.
PS> 'foo' | % Replace f F
Foo
Reg key
or theFolder
exists or not. I just keep go on usingtab
so that I get to place where I want usingauto-suggestion
and to call something now, all of sudden I have to wrap it from the start can call a method. It's really pain – Czarevitch