$ _和[参数(ValueFromPipeline = $ true)]之间的奇怪差异

Vim*_*mes 3 powershell

我来到了我的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
Run Code Online (Sandbox Code Playgroud)

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] =
Run Code Online (Sandbox Code Playgroud)

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] =
Run Code Online (Sandbox Code Playgroud)

CB.*_*CB. 8

根据我的评论$input是一个保留的自动变量.如果您pipedparameterfunction使用另一个命名变量更改它,您将具有预期的行为.