Reputation: 63
I am learning PowerShell and trying to figure out if I can just create one loop to get the following output.
$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
}
}
output: here is name starts with Ri: Rick Riah Rio, here is name starts with Ro: Rocky Rob, here is name starts with Jo: John Joab, here is name starts with Ja:James
Upvotes: 1
Views: 60
Reputation: 8878
Consider this. You can get the output of the names without a loop with regex -Match
with the '|' (or) regex operator
$array = "Rick","John","James","Rocky","Smith", "Rob", "Joab","Riah","Rio"
$array -match 'Ri|Ro|Jo|Ja'
Output
Rick
John
James
Rocky
Rob
Joab
Riah
Rio
You could parameterize the foreach loop
'Ri','Ro','Jo','Ja' | Foreach-Object {
write-Host "here is name starts with $_ :"
$array -like "$_*"
}
Output
here is name starts with Ri :
Rick
Riah
Rio
here is name starts with Ro :
Rocky
Rob
here is name starts with Jo :
John
Joab
here is name starts with Ja :
James
Or even use a switch statement
Switch -Regex ($array){
'Ri' {$_}
'Ro' {$_}
'Jo' {$_}
'Ja' {$_}
}
Output
Rick
John
James
Rocky
Rob
Joab
Riah
Rio
Upvotes: 2
Reputation: 357
If you create another array for the starts you want to match, you can have a single loop. Like this:
$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 { $_ }
}
If do not want to, or can have another loop, you will have to have one loop for each test:
$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 { $_ }
Upvotes: 2