Skip to content

Instantly share code, notes, and snippets.

@gpduck
Created February 21, 2017 18:40
Show Gist options
  • Save gpduck/d7d8a85d7400733a5404dfc835ea6c0c to your computer and use it in GitHub Desktop.
Save gpduck/d7d8a85d7400733a5404dfc835ea6c0c to your computer and use it in GitHub Desktop.

The PowerShell pipeline unwraps collections. Let's write a function to test to see if something is a collection

function Test-Collection {
  param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    $InputObject
  )
  process {
     $InputObject -is [System.Collections.ICollection]
  }
}

You can run the following to see how different input arrives at the body of the function:

# This returns False
Test-Collection 1

# This returns True
Test-Collection 1,2

# This returns False False because PS unwraps the array passing 1 and then 2 individually to the process block.
1,2 | Test-Collection

# This makes use of the fact that PS only unwraps 1 level of collection to pass a full collection to the function
# (It will return True)
,@(1,2) | Test-Collection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment