通过PowerShell中的Foreach循环动态标点和语法纠正字符串

时间:2013-09-25 18:35:20

标签: arrays string powershell formatting punctuation

我在PowerShell脚本中有一个简单的部分,它遍历列表中的每个数组并抓取数据(在当前数组的[3]处找到),使用它来确定数组的另一部分(在[找到] 0])应该添加到字符串的末尾。

$String = "There is"

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

这样做很好,花花公子,导致$String类似

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

但遗憾的是,对于我想要的内容,这并没有真正意义上的理解。我知道我可以在创建字符串后修复它,或者在foreach / if语句中包含用于确定要添加的字符的行。这需要:

  • $String += " a " + $_[0] - 第一场比赛。
  • $String += ", a " + $_[0] - 用于以下匹配。
  • $String += " and a " + $_[0] + " here." - 最后一场比赛。

此外,如果$_[0]以辅音开头,我需要确定是否使用“a”;如果$_[0]以元音开头,我需要确定是否使用“a”。总而言之,我希望输出为

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

谢谢!

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

$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.'