powershell - Powershell:从两个或多个循环中中断
问题描述
我有一个脚本可以 ping 系统直到它被终止。主代码块是一个函数,它有一个 foreach 循环嵌套在一个 do until 循环中。
## Start
function start-skript{
Write-Output 'Ping läuft...'
$Repetition_Counter = 0
#Start loop
do {
#Host loop
foreach($system in $Hosts_Array) {
#Ping Function
Ping-Host -HostToPing $system
#Write-Host 'Sleep for' $Pause 'sekunde'
Start-Sleep -Seconds $Pause
} $Repetition_Counter ++
} until($Repetition_Counter -eq $Repetition -or (stop-script))
}
start-skript
它工作正常。但是,通过调用 stop-script 函数,脚本只能在 ping-host 函数应用于 $Hosts_Array 中的所有设备后才能停止。我希望能够通过调用 stop-script 函数来停止脚本,即使功能 Ping-host 尚未应用于 $Hosts_Array 数组中的所有设备。我想,我可以像下面那样做
## Start
function start-skript{
Write-Output 'Ping läuft...'
$Repetition_Counter = 0
#Start loop
do {
#Host loop
foreach($system in $Hosts_Array) {
#Ping Function
Ping-Host -HostToPing $system
#Write-Host 'Sleep for' $Pause 'sekunde'
**stop-script** ## I've just added the function here
Start-Sleep -Seconds $Pause
} $Repetition_Counter ++
} until($Repetition_Counter -eq $Repetition -or (stop-script))
}
start-skript
我没有工作。它刚从 foreach 循环中出来,然后又从 foreach 循环开始,bcz foreach 循环进入了 do until 循环。有什么建议吗?
解决方案
使用语句标签:
:outer
do
{
:inner
foreach($i in 1..10){
if($i -eq 2){
continue inner
}
if($i -gt 5){
break outer
}
$i
}
}while($true)
输出将是:
1
3
4
5
因为我们continue
打开了内循环并在$i -eq 2
之后打破了外循环$i -eq 5
推荐阅读
- c# - 使用 PInvoke 包装的 C++ 库的并行调用引发 System.AccessViolationException
- r - 安装 R 包 PearsonDS 给出了意外的令牌错误
- python - Bokeh 2.0 中的简单日期范围滑块
- swift - “前提条件失败:类型检查失败:104,预期图像,得到 _ColorInvertEffect”,在 iOS 13.4 上的 SwiftUI 中使用 .colorInvert()
- haskell - 在 Haskell 中实现 Lambda 演算的模式匹配
- if-statement - 简单的编辑检查以通过电子邮件发送不工作的人
- python - python中的多级依赖注入
- python - Pandas drop_duplicates only possible after to_csv and read_csv
- r - 组合多列/堆叠多列
- java - ConnectyCube 检索对话框列表返回一个空列表