Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function Measure-Frequency {
<#
.SYNOPSIS
Get the frequency distribution of a set.
.DESCRIPTION
This function will get the frequency distribution of a set (array) of data.
It supports array types, as well as strings.
.EXAMPLE
Measure-Frequency $array
.EXAMPLE
Measure-Frequency $string -CaseSensitive
.NOTES
Author: Øyvind Kallstad
Date: 10.02.2016
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
$InputObject,
[Parameter()]
[switch] $CaseSensitive
)
try {
if ($InputObject.GetType().Name -eq 'String') {
if ($CaseSensitive) {
$inputArray = $InputObject.ToCharArray()
}
else {
$inputArray = $InputObject.ToLower().ToCharArray()
}
}
else {
$inputArray = $InputObject
}
$inputArray | Group-Object | Sort-Object -Descending -Property Count | ForEach-Object {
$frequency = $_.Count / $inputArray.Length
$percent = '{0:P0}' -f $frequency
Write-Output ([PSCustomObject] [Ordered] @{
Value = $_.Name
Count = $_.Count
Percent = $percent
Frequency = $frequency
})
}
}
catch {
Write-Warning $_.Exception.Message
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment