2013-09-25 31 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.'