在PowerShell中嵌套ForEach() [英] Nested ForEach() in PowerShell

查看:896
本文介绍了在PowerShell中嵌套ForEach()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PowerShell中嵌套ForEach循环时遇到了一些麻烦。首先,我需要迭代列表1.对于列表1中的每个对象,我需要遍历列表2.当我在列表2中找到类似的对象时,我想要转到列表1中的下一个对象。



我尝试过休息,我试过继续,但是对我来说不起作用。

 $ $ b $ ForEach($ objectA in $ listA){
ForEach($ objectB in $ listB){
if($ objectA -eq $ objectB ){
//做某事
//转到列表A中的下一个对象并找到下一个相等的对象
}
}
}
}

a)PowerShell中的中断/继续有什么作用?



b)我应该如何征服我的问题?

解决方案

c $ c> get-help about_break :
$ b

  Break语句可以包含一个标签。如果在
a标签中使用Break关键字,则Windows PowerShell会退出标签循环而不是退出
当前循环

像这样,

  foreach($ objectA in @(a,e, i)){
objectA:$ objectA
:outer
foreach($ objectB in @(a,b,c,d,如果($ objectB -eq $ objectA){
hit!$ objectB
break:outer
} else {miss!$ objectB}
}
}

#输出:
objectA:
命中!
objectA:e
想念!
小姐! b
错过! c
错过! d
命中! e
objectA:i
错过!
小姐! b
错过! c
错过! d
错过! e


I'm having some troubles with nested ForEach loops in Powershell. First, I need to iterate through list 1. For every object in list 1, I need to iterate through list 2. When I found the resembling object in list 2, I want to go to the next object in list 1.

I've tried break, i've tried continue, but it won't work for me.

Function checkLists() {
  ForEach ($objectA in $listA) {
    ForEach ($objectB in $listB) {
       if ($objectA -eq $objectB) {
           // Do something 
           // goto next object in list A and find the next equal object
       }
    }
  }
}

a) What does a break/continue exactly do in PowerShell?

b) How exaclty should I conquer my 'problem'?

解决方案

Use a label as described in get-help about_break:

A Break statement can include a label. If you use the Break keyword with
a label, Windows PowerShell exits the labeled loop instead of exiting the
current loop

Like so,

foreach ($objectA in @("a", "e", "i")) {
    "objectA: $objectA"
    :outer
    foreach ($objectB in @("a", "b", "c", "d", "e")) {
       if ($objectB -eq $objectA) {
           "hit! $objectB"
           break :outer
       } else { "miss! $objectB" }
    }
}

#Output:
objectA: a
hit! a
objectA: e
miss! a
miss! b
miss! c
miss! d
hit! e
objectA: i
miss! a
miss! b
miss! c
miss! d
miss! e

这篇关于在PowerShell中嵌套ForEach()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆