2012-11-21 100 views
2

我已經到了我的PoweShell-fu的邊緣。有人可以向我解釋爲什麼這兩個函數在管道陣列數組時有不同的作用?所有不同的是,我是使用$_還是[parameter(ValueFromPipeline=$true)] $input來獲取管道輸入。我期望這些人在這種情況下采取相同的行動。

$pairs = ('a', 'b'), ('c', 'd') 

function dollarUnderscoreFunction 
{ 
    Process 
    { 
     Write-Host "`$_[0] = $($_[0])" 
     Write-Host "`$_[1] = $($_[1])" 
    } 
} 

function pipedParameterFunction([parameter(ValueFromPipeline=$true)] $input) 
{ 
    Process 
    { 
     Write-Host "`$input[0] = $($input[0])" 
     Write-Host "`$input[1] = $($input[1])" 
    } 
} 

Write-Host "`$pairs:" 
$pairs | foreach { Write-Host $_ } 

Write-Host "`nRunning dollarUnderscoreFunction`n" 
$pairs | dollarUnderscoreFunction 

Write-Host "`nRunning pipedParameterFunction`n" 
$pairs | pipedParameterFunction 

輸出使用PowerShell v3的:

$pairs: 
a b 
c d 

Running dollarUnderscoreFunction 

$_[0] = a 
$_[1] = b 
$_[0] = c 
$_[1] = d 

Running pipedParameterFunction 

$input[0] = a b 
$input[1] = 
$input[0] = c d 
$input[1] = 

輸出使用PowerShell V2:

$pairs: 
a b 
c d 

Running dollarUnderscoreFunction 

$_[0] = a 
$_[1] = b 
$_[0] = c 
$_[1] = d 

Running pipedParameterFunction 

[ : Unable to index into an object of type System.Collections.ArrayList+ArrayListEnumeratorSimple. 
At C:\Untitled1.ps1:16 char:8 
+ $input[ <<<< 0] 
    + CategoryInfo   : InvalidOperation: (0:Int32) [], RuntimeException 
    + FullyQualifiedErrorId : CannotIndex 

$input[0] = 
[ : Unable to index into an object of type System.Collections.ArrayList+ArrayListEnumeratorSimple. 
At C:\Untitled1.ps1:17 char:8 
+ $input[ <<<< 1] 
    + CategoryInfo   : InvalidOperation: (1:Int32) [], RuntimeException 
    + FullyQualifiedErrorId : CannotIndex 

$input[1] = 
[ : Unable to index into an object of type System.Collections.ArrayList+ArrayListEnumeratorSimple. 
At C:\Untitled1.ps1:16 char:8 
+ $input[ <<<< 0] 
    + CategoryInfo   : InvalidOperation: (0:Int32) [], RuntimeException 
    + FullyQualifiedErrorId : CannotIndex 

$input[0] = 
[ : Unable to index into an object of type System.Collections.ArrayList+ArrayListEnumeratorSimple. 
At C:\Untitled1.ps1:17 char:8 
+ $input[ <<<< 1] 
    + CategoryInfo   : InvalidOperation: (1:Int32) [], RuntimeException 
    + FullyQualifiedErrorId : CannotIndex 

$input[1] = 
+1

嘗試在您的pipedparameterfunction中使用另一個命名變量chnage $ input變量。 $ Input是一個自動變量。 –

+0

**/facepalm **謝謝,基督徒!如果您將其作爲答案張貼,我會標記它。 – Vimes

+0

做了我的答案! :) –

回答

7

按我的意見$input是一個保留automatic variable。 如果使用另一個命名變量在pipedparameterfunction中對其進行更改,則會出現預期行爲。

相關問題