Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/d76791ca0c058544d6a4 to your computer and use it in GitHub Desktop.
Save guitarrapc/d76791ca0c058544d6a4 to your computer and use it in GitHub Desktop.
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