Created
August 15, 2012 10:30
-
-
Save heaths/3358559 to your computer and use it in GitHub Desktop.
Select-Unique
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Select-Unique | |
| { | |
| [CmdletBinding()] | |
| param | |
| ( | |
| [Parameter(Mandatory=$true, Position=0)] | |
| [string[]] $Property, | |
| [Parameter(Mandatory=$true, ValueFromPipeline=$true)] | |
| $InputObject, | |
| [Parameter()] | |
| [switch] $AsHashtable, | |
| [Parameter()] | |
| [switch] $NoElement | |
| ) | |
| begin | |
| { | |
| $Keys = @{} | |
| } | |
| process | |
| { | |
| $InputObject | foreach-object { | |
| $o = $_ | |
| $k = $Property | foreach-object -begin { | |
| $s = '' | |
| } -process { | |
| # Delimit multiple properties like group-object does. | |
| if ( $s.Length -gt 0 ) | |
| { | |
| $s += ', ' | |
| } | |
| $s += $o.$_ -as [string] | |
| } -end { | |
| $s | |
| } | |
| if ( -not $Keys.ContainsKey($k) ) | |
| { | |
| $Keys.Add($k, $null) | |
| if ( -not $AsHashtable ) | |
| { | |
| $o | |
| } | |
| elseif ( -not $NoElement ) | |
| { | |
| $Keys[$k] = $o | |
| } | |
| } | |
| } | |
| } | |
| end | |
| { | |
| if ( $AsHashtable ) | |
| { | |
| $Keys | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Select-Unique
PowerShell's built-in
select-objectcmdlet has a-uniqueparameter that introduces significant performance issues and loss of information. Myselect-uniquecmdlet works around those issues.Performance
The performance issue is because
select-objectenumerates and collects all objects before selecting unique objects based on the objects' properties you specify.select-uniqueouputs objects while enumerating and keeps track of which unique combination of objects' properties has already been enumerated.Information loss
Because
select-objectonly outputs those properties, you can't select unique objects and output all properties.select-uniqueis more like a filter.Comparison
Consider that you want to see all the files with unique file extensions in a directory recursively.
select-object -uniquewould output only the extensions:select-uniquewill, however, output all properties (while maintaining the default type view) and will output objects as they are processed through the pipeline, allowing downstream cmdlets to process those objects as they come.