我正在尝试了解如何pipe |
一个对象并调用该属性或方法。
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
我可以在其上输出Get-Item
和invoke properties/methods
的输出吗?
Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\ | call GetSomething()
答案 0 :(得分:2)
排序答案是否。你不能使用Pipeline来调用这样的方法。但是你可以在括号中包围你的Get-Item
调用并调用它:
(Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\).GetSomething()
如果您不想要,可以滥用Select-Object
cmdlet:
Get-Item Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Test\abc\ | select { $_.GetSomething() }
答案 1 :(得分:1)
如果不写一些东西就不可能做到这一点。那件事会让人很困惑。
喜欢这个。
filter Invoke-Method {
param(
[String]$Method,
[Object[]]$ArgumentList
)
$_.GetType().InvokeMember(
$Method.Trim(),
([System.Reflection.BindingFlags]'InvokeMethod'),
$null,
$_,
$ArgumentList
)
}
"qwerty" | Invoke-Method Replace 'q', 'z'
属性更容易,因为已有命令执行此操作:
(...).GetSomething() | Select-Object Property1, Property2
答案 2 :(得分:0)
我认为一种更好的方法是使用例如:
{ "type": "num", "targets": 3 }
:
其中Get-Item Registry::HKLM | % { $_ }
为%
(即使您只有1,也可以使用),ForEach-Object
是每个对象。
答案 3 :(得分:0)
Ansgar Wiechers在评论Martin Brandl的答案时提供了关键指针:
规范的方式为
ForEach-Object
。可以使用别名%
非常简洁地编写:
... | % { $_.GetSomething() }
在PowerShell版本3或更高版本中,您使用operation statement 使呼叫更加简洁,从而无需将呼叫包含在{ ... }
中,而不必显式引用$_
,并且需要使用括号((...)
):
... | % GetSomething # short for: ... | ForEach-Object GetSomething
请注意,如果该方法采用参数,则必须以 array ({,
分隔)的形式提供参数,但不能将其包含在(...)
,因为语法上的参数是在argument mode中传递的,这也使得对简单字符串值的引用是可选的-请参见下面的示例。
示例:
没有参数的方法调用 :
# 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
使用一个参数的方法调用:
# 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
具有多个参数的方法调用:
# Perform the equivalent of 'foo'.Replace('f', 'F'); i.e.,
# replace all lowercase Fs with uppercase ones.
PS> 'foo' | % Replace f F
Foo
答案 4 :(得分:0)
在大多数情况下,此要求表明可以通过更简单的方式来完成任务。
但是,如果确实需要,可以使用MemberName
cmdlet的ForEach-Object
参数:
# declare something
$o = @{
One = 1
Two = 2
Three = 6
}
# do something
$o |
ForEach-Object -MemberName "GetEnumerator" |
ForEach-Object { "$($_.Key): $($_.Value)" } |
Write-Host