Skip to content

Instantly share code, notes, and snippets.

@guitarrapc guitarrapc/ArrayMap.ps1
Last active Aug 29, 2015

Embed
What would you like to do?
LINQ SelectMany for PowerShell
SelectMany -Source (1,2),(3,4) {$Source | %{"OU={0}" -f $_}} -Verbose
<#
詳細: 1 2
詳細: OU=1 OU=2
OU=1
OU=2
詳細: 3 4
詳細: OU=3 OU=4
OU=3
OU=4
#>
SelectMany -Source (1,2),(3,4)
<#
1
2
3
4
#>
SelectMany -Source (1,2),(3,4) | measure
<#
Count : 4
#>
SelectMany -Source 1,2,(3,4) {$Source | %{"OU={0}" -f $_}} -Verbose
<#
詳細: 1
詳細: OU=1
OU=1
詳細: 2
詳細: OU=2
OU=2
詳細: 3 4
詳細: OU=3 OU=4
OU=3
OU=4
#>
1,2,(3,4) | SelectMany -ScriptBlock {$Source | %{"OU={0}" -f $_}} -Verbose
<#
詳細: 1
詳細: OU=1
OU=1
詳細: 2
詳細: OU=2
OU=2
詳細: 3
詳細: OU=3
OU=3
詳細: 4
詳細: OU=4
OU=4
#>
#Requires -Version 4.0
function SelectMany
{
[CmdletBinding()]
param
(
[parameter(Mandatory = 1, Position = 0, ValueFromPipeline = 1)]
[PSObject[]]$Source,
[parameter(Mandatory = 0, Position = 1)]
[ScriptBlock]$ScriptBlock = {$Source}
)
process
{
foreach ($x in $Source)
{
$output = $ScriptBlock.GetNewClosure().InvokeWithContext(
$null,
(New-Object "System.Management.Automation.PSVariable" ("Source", $x))
)
foreach ($o in $output)
{
$o
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.