我在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."
谢谢!
最佳答案
尝试这样的事情:
$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.'