Search code examples
arraysstringpowershellformattingpunctuation

Dynamically punctuating and grammatically correcting a string via a Foreach loop in PowerShell


I have a simple section in a PowerShell script that goes through each array in a list and grabs the data (found at [3] of the current array), using it to determine if another part of the array (found at [0]) should be added to the end of a string.

$String = "There is"

$Objects | Foreach-Object{
if ($_[3] -match "YES")
    {$String += ", a " + $_[0]}
}

This works fine and dandy, resulting in a $String of something like

"There is, a car, a airplane, a truck"

But unfortunately this doesn't really make sense grammatically for what I want. I'm aware that I could either fix the string after it's been created, or include lines in the foreach/if statement that determine which characters to add. This would need to be:

  • $String += " a " + $_[0] - for the first match.
  • $String += ", a " + $_[0] - for following matches.
  • $String += " and a " + $_[0] + " here." - for the last match.

Furthermore I need to determine whether to use " a " if $_[0] starts with a consonant, or " an " if $_[0] starts with a vowel. All in all, I'd like the output to be

"There is a car, an airplane and a truck here."

Thanks!


Solution

  • Try something like this:

    $vehicles = $Objects | ? { $_[3] -match 'yes' } | % { $_[0] }
    
    $String = 'There is'
    for ($i = 0; $i -lt $vehicles.Length; $i++) {
      switch ($i) {
        0                    { $String += ' a' }
        ($vehicles.Length-1) { $String += ' and a' }
        default              { $String += ', a' }
      }
      if ($vehicles[$i] -match '^[aeiou]') { $String += 'n' }
      $String += ' ' + $vehicles[$i]
    }
    $String += ' here.'