2015-04-07 26 views
3

Join-Path據稱接受來自管道的Path參數。當通過管道傳遞路徑時Powershell的加入路徑錯誤

這表明,下面的兩個功能都應該一樣工作:

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

但是第二次調用(即使用按值傳遞路徑參數的管線)給出了以下錯誤:

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中的錯誤?

回答

3

在第一個例子中,一個表達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' 
+0

啊;因此通過管道傳遞參數1不會導致參數2向上移動鏈。稍微煩人的語言設計,但至少它是有道理的;謝謝。 – JohnLBevan

+2

@JohnLBevan,我只是說參數綁定發生在表達式解析階段,解析器知道您將要從管道傳遞某些東西。 – ForNeVeR

+0

謝謝@ForNeVeR;很高興知道這種設計選擇有一個潛在的原因。 – JohnLBevan