powershell - 在 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 开头的名称
解决方案
如果为要匹配的开始创建另一个数组,则可以有一个循环。像这样:
$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 { $_ }
推荐阅读
- mongodb - 用于自动 Mongodb 备份的 Windows 批处理脚本
- video-streaming - 与 NanoPi NEO Core2 相关的硬件和网络问题
- javascript - 使用javascript从url获取文件名
- javascript - 我可以嵌入吗
标记成
标签?
- docker - 如何创建允许我根据命令行参数创建两个不同容器的 Dockerfile?
- c++ - Eigen Vector*Scalar + Vector*Scalar 的未定义行为 --> libigl/external/eigen 和其他特征冲突
- sql - 无法使用 SSIS OLE DB Provider 连接到 DB2 z/OS
- asp.net - 实体框架不跟踪列表
- c# - 将一系列随机数写入 C# 中的文件不起作用。打印相同的数字。我该如何解决这个问题?
- php - PHP 警告中的 mysqli 问题:mysqli_stmt_prepare() 需要参数 1