通过管道传递路径时出现 Powershell 加入路径错误

Powershell's Join-Path Errs when Passing Path via Pipeline

Join-Path 据称接受来自管道的 Path 参数。

这表明以下两个函数的工作原理应该相似:

join-path 'c:\temp' 'x'     #returns c:\temp\x
'c:\temp' | join-path 'x'   #throws an error

但是第二次调用(即使用按值将 Path 参数传递给管道)出现以下错误:

join-path : 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. At line:1 char:13 + 'c:\temp' | join-path 'x' + ~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (c:\temp:String) [Join-Path], ParameterBindingException + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.JoinPathCommand

注意:由于 path 可能是一个数组,我也尝试了 [array]('c:\temp') | join-path 'x';但这没有什么区别。

我是不是误解了什么,或者这是 PowerShell 中的错误?

在您的第一个示例中,表达式 join-path 'c:\temp' 'x' 被 PowerShell 解释为 Join-Path -Path 'c:\temp' -ChildPath 'x'(因为位置参数 PathChildPath 的名称是可选的)。

在您的第二个示例中,您将管道参数 'c:\temp' 传递给命令 Join-Path -Path 'x'(而不是缺少 ChildPath 参数)。它不会工作,因为 Join-Path 仅接受来自管道的 Path 参数,但您已经定义了它。

如果你想绑定另一个,而不是第一个参数,你应该明确地写它的名字,如

'c:\temp' | Join-Path -ChildPath 'x'
# => 'c:\temp\x'