Skip to content

Instantly share code, notes, and snippets.

@thedavecarroll
Last active November 19, 2022 04:23
Show Gist options
  • Save thedavecarroll/65b6f1b35b848a63ebb92773b2554927 to your computer and use it in GitHub Desktop.
Save thedavecarroll/65b6f1b35b848a63ebb92773b2554927 to your computer and use it in GitHub Desktop.
The Join-OxfordComma command can provide you a comma separated list using the Oxford comma and either 'and' or 'or'.
function Join-OxfordComma {
[CmdletBinding(DefaultParameterSetName='And')]
[Alias('jox')]
param(
[Parameter(Mandatory,ValueFromPipeline)]
[string[]]$JoinList,
[Parameter(ParameterSetName='And')]
[switch]$And,
[Parameter(ParameterSetName='Or')]
[switch]$Or
)
begin {
$List = [System.Collections.Generic.List[string]]::new()
$Type = if ($PSCmdlet.ParameterSetName -eq 'And') { 'and' } else { 'or' }
}
process {
foreach ($Item in $JoinList) {
$List.Add($Item)
}
}
end {
switch ($List.Count) {
1 { $List }
2 { '{0} {1} {2}' -f $List[0],$Type,$List[1]}
default {
'{0}, {1} {2}' -f ($List[0..($List.count-2)] -join ', '),$Type,$List[-1]
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment