gpt4 book ai didi

powershell - 为什么我不能在 write-host 中使用 $_?

转载 作者:行者123 更新时间:2023-12-02 23:35:48 25 4
gpt4 key购买 nike

我正在尝试将字符串数组通过管道传输到 write-host 并显式使用 $_写这些字符串:

'foo', 'bar', 'baz' | write-host $_

但是,它失败了:

The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.



这个错误信息对我来说毫无意义,因为我完全可以写
'foo', 'bar', 'baz' | write-host

我本来希望两个管道是等效的。显然,他们不是。那么,有什么区别呢?

最佳答案

I would have expected both pipelines to be equivalent.


他们不是:

'foo', 'bar', 'baz' | write-host


它是以下基于管道的等价物(最终效果等价,而不是技术上的等价物):
foreach ($str in 'foo', 'bar', 'baz') { Write-Host -Object $str }
也就是说,在您的命令中 Write-Host从隐式绑定(bind)到其 -Object 的管道接收输入每个输入对象的参数,凭借参数 -Object通过属性 [Parameter(ValueFromPipeline=$true)] 声明为接受管道输入

'foo', 'bar', 'baz' | write-host $_


在管道处理开始之前,参数 - $_在您的情况下-首先绑定(bind)到参数:
由于 $_前面没有参数名称,它在位置上绑定(bind)到 - 隐含 - -Object范围。
然后,当管道处理开始时,管道参数绑定(bind)发现没有管道绑定(bind) Write-Host考虑到唯一这样的参数 -Object 再绑定(bind)到的参数已经被绑定(bind),即被一个参数 $_ .
换句话说: 您的命令错误地尝试绑定(bind) -Object参数两次; 不幸的是,错误消息并没有完全说明这一点。
更大的一点是 使用 $_只有在脚本 block 内才有意义( { ... } )对每个输入对象进行评估。
在这种情况下, $_ (或其别名 $PSItem )通常没有值(value),不应使用。
$_最常用于传递给 ForEach-Object 的脚本 block 中。和 Where-Object cmdlet,还有其他有用的应用程序,最常见的是 Rename-Item cmdlet:一个 delay-bind script-block argument :
# Example: rename *.txt files to *.dat files using a delay-bind script block:
Get-Item *.txt | Rename-Item -NewName { $_.BaseName + '.dat' }
也就是说,不是将静态新名称传递给 Rename-Item。 ,您传递一个脚本 block ,该 block 针对每个输入对象进行评估 - 输入对象绑定(bind)到 $_ ,像往常一样 - 启用动态行为。
然而,正如链接答案中所解释的那样,该技术仅适用于 (a) 管道绑定(bind)和 (b) 不是 [object] 的参数。或 [scriptblock]打字;因此,鉴于 Write-Object-Object参数为 [object]键入,该技术不起作用:
 # Try to enclose all inputs in [...] on output.
# !! DOES NOT WORK.
'foo', 'bar', 'baz' | write-host -Object { "[$_]" }
因此,基于管道的解决方案需要使用 ForEach-Object在这种情况下:
# -Object is optional
PS> 'foo', 'bar', 'baz' | ForEach-Object { write-host -Object "[$_]" }
[foo]
[bar]
[baz]

关于powershell - 为什么我不能在 write-host 中使用 $_?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55665530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com