首页 > 解决方案 > 在 Powershell 中进行一次 foreach 迭代而不是 4 次

问题描述

我正在学习 PowerShell 并试图弄清楚我是否可以只创建一个循环来获得以下输出。

$array = "Rick","John","James","Rocky","Smith", "Rob", "Joab","Riah","Rio"

foreach($nameMatch in $array){
if($nameMatch -like 'Ri*'){
write-Host "here is name starts with Ri:" $nameMatch
}
}

foreach($nameMatch in $array){
if($nameMatch -like 'Ro*'){
write-Host "here is name starts with Ro:" $nameMatch
}
}
foreach($nameMatch in $array){
if($nameMatch -like 'Jo*'){
write-Host "here is name starts with Jo:" $nameMatch
}
}
foreach($nameMatch in $array){
if($nameMatch -like 'Ja*'){
write-Host "here is name starts with Ja:" $nameMatch
}
}

输出:这是以 Ri 开头的名称:Rick Riah Rio,这是以 Ro 开头的名称:Rocky Rob,这是以 Jo:John Joab 开头的名称,这是以 Ja:James 开头的名称

标签: powershell

解决方案


如果为要匹配的开始创建另一个数组,则可以有一个循环。像这样:

$array = "Rick","John","James","Rocky","Smith", "Rob", "Joab","Riah","Rio"
$toMatch = "Ri","Ro","Jo","Ja"

foreach ( $m in $toMatch )
{
    Write-Host "`nHere is names starts with $m :"
    $array | where { $_ -match "^$m" } | foreach { $_ }
}

如果不想,或者可以有另一个循环,则每个测试都必须有一个循环:

$array = "Rick","John","James","Rocky","Smith", "Rob", "Joab","Riah","Rio"

Write-Host "`nHere is name starts with Ri:"
$array | where { $_ -match "^Ri" } | foreach { $_ }

Write-Host "`nHere is name starts with Ro:"
$array | where { $_ -match "^Ro" } | foreach { $_ }

Write-Host "`nHere is name starts with Jo:"
$array | where { $_ -match "^Jo" } | foreach { $_ }

Write-Host "`nHere is name starts with Ja:"
$array | where { $_ -match "^Ja" } | foreach { $_ }

推荐阅读