Skip to content

Instantly share code, notes, and snippets.

@ninmonkey
Last active May 26, 2024 02:16
Show Gist options
  • Save ninmonkey/c7ffd31ef616ab90353f469a46e6ddc4 to your computer and use it in GitHub Desktop.
Save ninmonkey/c7ffd31ef616ab90353f469a46e6ddc4 to your computer and use it in GitHub Desktop.
PowerShell Selecting First, Last, One, Some, script.ps1

Features

> stuff | One # returns first only
> stuff | Some # returns first 5
> stuff | Some -FromEnd # same, but in reverse
  • also saves one and some's result to the variables $global:One and $global:Some
  • It always returns the real, original objects
  • It summarizes typenames and sizes, without breaking those objects in the output stream

Optional functions used, that are overkill

The lines CountOf | Format-ShortTypeName are optional. They are in some dotfiles

Other Versions

SeeminglySciences profile, this discord thread has more context

I don't have an easily copy pasted version, and unfortunately it's quite involved, but I do have one in my profile: the actual function: https://github.com/SeeminglyScience/dotfiles/blob/bc31aaaec30343be4788d47b2c08b40d6763268d/Documents/PowerShell/Utility.psm1#L3327-L3355

required context (also the complicated part): https://github.com/SeeminglyScience/dotfiles/blob/bc31aaaec30343be4788d47b2c08b40d6763268d/Documents/PowerShell/Utility.psm1#L132-L267

using namespace System.Collections.Generic
Import-module Pansies
function Dotfiles.Select-Some {
<#
.SYNOPSIS
select 1 item, 5, or a specific count.
.NOTES
- [ ] future: rewrite using steppable pipeline for an earlier exit
.EXAMPLE
Get-Process | One # returns 1 item
Get-Command | Some # returns 5 items
Get-Process | Some 3 # returns 3 item
... | Some -LastOne
#>
[Alias('Some', 'One')]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[object] $InputObject,
[Alias('Count', 'Limit')]
[Parameter(Position = 0)]
[int] $FirstN = 5,
[switch] $LastOne
)
begin {
[bool]$IsUsingOne = $MyInvocation.InvocationName -eq 'One'
[List[Object]]$Items = @()
$selectSplat = @{}
if( $IsUsingOne ) { $FirstN = 1 }
if( $LastOne ) { $selectSplat.Last = $FirstN }
else { $selectSplat.First = $FirstN }
}
process {
$Items.AddRange(@( $InputObject ))
}
end {
$query = $Items | Select @SelectSplat
if($IsUsingOne) {
$Query
$global:One = $Query
'One := {0}' -f @(
$Global:One | Format-ShortTypeName
) | New-Text -fg 'gray60' -bg 'gray20'
| Write-Information -infa Continue
} else {
$Query
$global:Some = $query
'Some := {0}' -f @(
$global:Some
| CountOf | Format-ShortTypeName
) | New-Text -fg 'gray60' -bg 'gray20'
| Write-Information -infa Continue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment