2013-09-25 29 views
2

我在PowerShell脚本中有一个简单的部分,它贯穿列表中的每个数组并获取数据(在当前数组的[3]中找到),使用它确定数组的另一部分(位于[0]处)是否应添加到字符串的末尾。PowerShell中通过Foreach循环动态标点符号和语法纠正

$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." - 最后一场比赛。

此外,我需要确定是否使用“A”,如果$_[0]与辅音,“一个”,如果$_[0]开始以元音开头。总而言之,我想输出为

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

谢谢!

回答

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