前回、 PowerShellが熱心にコレクションをアンロールする方法に戸惑いましたが、Keith はそのヒューリスティックを次のようにまとめました。
結果 (配列) をグループ化式 (または $() などの部分式) 内に配置すると、再度展開できるようになります。
私はそのアドバイスを心に留めていますが、それでもいくつかの難解なことを説明することはできません. 特に、Format オペレーターはルールに従っていないようです。
$lhs = "{0} {1}"
filter Identity { $_ }
filter Square { ($_, $_) }
filter Wrap { (,$_) }
filter SquareAndWrap { (,($_, $_)) }
$rhs = "a" | Square
# 1. all succeed
$lhs -f $rhs
$lhs -f ($rhs)
$lhs -f $($rhs)
$lhs -f @($rhs)
$rhs = "a" | Square | Wrap
# 2. all succeed
$lhs -f $rhs
$lhs -f ($rhs)
$lhs -f $($rhs)
$lhs -f @($rhs)
$rhs = "a" | SquareAndWrap
# 3. all succeed
$lhs -f $rhs
$lhs -f ($rhs)
$lhs -f $($rhs)
$lhs -f @($rhs)
$rhs = "a", "b" | SquareAndWrap
# 4. all succeed by coercing the inner array to the string "System.Object[]"
$lhs -f $rhs
$lhs -f ($rhs)
$lhs -f $($rhs)
$lhs -f @($rhs)
"a" | Square | % {
# 5. all fail
$lhs -f $_
$lhs -f ($_)
$lhs -f @($_)
$lhs -f $($_)
}
"a", "b" | Square | % {
# 6. all fail
$lhs -f $_
$lhs -f ($_)
$lhs -f @($_)
$lhs -f $($_)
}
"a" | Square | Wrap | % {
# 7. all fail
$lhs -f $_
$lhs -f ($_)
$lhs -f @($_)
$lhs -f $($_)
}
"a", "b" | Square | Wrap | % {
# 8. all fail
$lhs -f $_
$lhs -f ($_)
$lhs -f @($_)
$lhs -f $($_)
}
"a" | SquareAndWrap | % {
# 9. only @() and $() succeed
$lhs -f $_
$lhs -f ($_)
$lhs -f @($_)
$lhs -f $($_)
}
"a", "b" | SquareAndWrap | % {
# 10. only $() succeeds
$lhs -f $_
$lhs -f ($_)
$lhs -f @($_)
$lhs -f $($_)
}
前の質問で見たのと同じパターンを適用すると、#1 と #5 のようなケースが異なる動作をする理由は明らかです。パイプライン オペレーターはスクリプト エンジンに別のレベルをアンロールするように信号を送りますが、割り当てオペレーターはそうしません。別の言い方をすれば、2 つの | の間にあるものはすべて、() の中にあるかのように、グループ化された式として扱われます。
# all of these output 2
("a" | Square).count # explicitly grouped
("a" | Square | measure).count # grouped by pipes
("a" | Square | Identity).count # pipe + ()
("a" | Square | Identity | measure).count # pipe + pipe
同じ理由で、ケース #7 は #5 よりも改善されていません。余分なラップを追加しようとすると、余分なパイプによってすぐに破壊されます。同上 #8 vs #6。少しイライラしますが、私はこの時点まで完全に参加しています。
残りの質問:
- ケース #3 が #4 と同じ運命をたどらないのはなぜですか? $rhsはネストされた配列(,("a", "a"))を保持する必要がありますが、その外側のレベルは展開されています...どこか...
- #9-10 のさまざまなグループ化演算子で何が起こっているのでしょうか? なぜ彼らはそんなに不規則に振る舞うのですか、そしてなぜ彼らは必要なのですか?
- #10 の場合の障害が #4 のように正常に劣化しないのはなぜですか?