3

パウシェルフーの限界に来ました。配列の配列をパイプするときに、これら 2 つの関数の動作が異なる理由を誰かが説明できますか? 異なるのは、パイプ入力を使用している$_か、取得するかだけです。[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] =
4

1 に答える 1

8

私のコメントによる$inputと、予約済みの自動変数です。別の名前付き変数でそれを変更するとpipedparameterfunction、期待される動作が得られます。

于 2012-11-21T22:35:03.273 に答える