【发布时间】:2022-01-12 09:10:12
【问题描述】:
在 Powershell 5 中
不明白,在调试这段代码的时候,为什么当匹配到主字符串末尾的字符串“of”时,方法不执行退出Class Method,继续迭代。
对我来说似乎违反直觉。
我必须使用辅助变量和结合break命令的标签吗?
类似这里:
:JUMPASFOX foreach ($i in (1..10)) {
...{break JUMPASFOX}
我认为 return $false 任何地方都会导致退出。 我无法协调我的代码不起作用。
Class EndFinder {
[string[]]$Exclusions_End_Text=@(" of", " of the", " of a", "for a", "for the", " in", " the")
EndFinder(){}
[boolean]Contains_Exclusion_At_The_End ([string]$ClipText) {
#$found=$false
$this.Exclusions_End_Text |foreach {
$exclusion_length=$_.Length
$clip_length=$ClipText.Length
if ($exclusion_length -lt $clip_length) {
$tailing=$ClipText.Substring($clip_length-$exclusion_length,$exclusion_length)
if ($tailing -eq $_) {
#$found=$true
return $true
}
}
}
return $false
#return $found
}
}
$kb=[EndFinder]::New()
$kb.Contains_Exclusion_At_The_End("big problem of the")
【问题讨论】:
-
发生这种情况是因为您使用
... |foreach {}(解析为... |ForEach-Object {})而不是真正的循环 -return将控制从脚本块返回给ForEach-Object命令,然后调用下一次迭代,忘记了你所期待的“直觉”行为。
标签: powershell