Here's a version using regex to determine which part of the input string to group by:
clear-host
'REGEX 1; org-dummyemail-123 vs org-dummyemail1-joemarmoto'
$groupedByAllButLast = @(
"org-dummyemail-123-AccountName",
"org-dummyemail-123-Email",
"org-dummyemail-123-PAT",
"org-dummyemail-123-PATName",
"org-dummyemail-123-PATValidTo",
"org-dummyemail1-joemarmoto-AccountName",
"org-dummyemail1-joemarmoto-Email",
"org-dummyemail1-joemarmoto-PAT",
"org-dummyemail1-joemarmoto-PATName",
"org-dummyemail1-joemarmoto-PATValidTo"
) | Group-Object -Property @{E={$_ -replace '([^-]+-[^-]+-[^-]+)-.*', '$1'}}
for ([int]$i = 0; $i -lt $groupedByAllButLast.Count; $i++)
{
Write-Verbose $groupedByAllButLast[$i].Name -Verbose
$groupedByAllButLast[$i].Group
}
'REGEX 2; 123 vs joemarmoto'
$groupedByTheNameOrEmailBit = @(
"org-dummyemail-123-AccountName",
"org-dummyemail-123-Email",
"org-dummyemail-123-PAT",
"org-dummyemail-123-PATName",
"org-dummyemail-123-PATValidTo",
"org-dummyemail1-joemarmoto-AccountName",
"org-dummyemail1-joemarmoto-Email",
"org-dummyemail1-joemarmoto-PAT",
"org-dummyemail1-joemarmoto-PATName",
"org-dummyemail1-joemarmoto-PATValidTo"
) | Group-Object -Property @{E={$_ -replace '[^-]+-[^-]+-([^-]+)-.*', '$1'}} #all we've changed is the location of the opening bracket in this line
for ([int]$i = 0; $i -lt $groupedByTheNameOrEmailBit.Count; $i++)
{
Write-Verbose $groupedByTheNameOrEmailBit[$i].Name -Verbose
$groupedByTheNameOrEmailBit[$i].Group
}
NB: This is basically the same approach as Lee's; only instead of using split and taking a signle segment, we use regex to capture all those parts of the string which are relevant for our key... See MS Docs for a bit more info on this useful function.
Group-Object -Property @{E={$_ -replace '[^-]+-[^-]+-([^-]+)-.8', '$1'}}to group by123/joemarmoto, orE={$_ -replace '([^-]+-[^-]+-[^-]+)-.8', '$1'}to group by all but the final field name.