PowerShell 中的嵌套 ForEach() [英] Nested ForEach() in PowerShell
问题描述
我在 Powershell 中遇到嵌套 ForEach 循环的一些问题.首先,我需要遍历列表 1.对于列表 1 中的每个对象,我需要遍历列表 2.当我在列表 2 中找到相似的对象时,我想转到列表 1 中的下一个对象.
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) PowerShell 中的 break/continue 究竟有什么作用?
a) What does a break/continue exactly do in PowerShell?
b) 我应该如何解决我的问题"?
b) How exaclty should I conquer my 'problem'?
推荐答案
使用 get-help about_break
中描述的标签:
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
就这样,
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屋!