首页 > 解决方案 > 从函数中的 Powershell 循环提前返回

问题描述

我正在尝试制作一个简单的“合并”功能,但在使用 Powershell 返回语法时遇到了困难

尝试:

function coalesce {
   foreach($item in $args) {
     if ($item) {
       return $item
       break # also tried continue and exit
     }
   }
 }
coalesce($nil,2,3)
2
3
function coalesce {
   ForEach-Object -InputObject $args { If($_) { return $_; exit } } # also tried continue and break
}
coalesce($nil,2,3)

2
3

那么如何return在任何其他编程语言中模拟退出函数的循环内部呢?

标签: powershellsyntax

解决方案


在powershell中,如果你调用一个用逗号分隔的项目包裹的parens的函数,你会得到一个对象。[ grin ] 您的函数正在运行并返回三个对象的数组。因此,使用三个输入调用该函数 的正确方法是......

coalesce $Null 2 3

另请注意,这$nil不是$Null......它是一个新变量nil,其中没有任何内容 - 换句话说,其中的值$Null


推荐阅读