0

I'm trying to make a simple "coalesce" function but struggling with Powershell return syntax

Attempts:

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

So how do I simulate a return inside a loop that exits the function in any other programming language?

mklement0
  • 382,024
  • 64
  • 607
  • 775
nijave
  • 489
  • 5
  • 11
  • what do you expect from that code? when i run it without the `break`, it returns the whole array as expected. you DO realize that by calling it with parens and commas you have made the input into ONE array, not 3 items? [*grin*] – Lee_Dailey May 23 '19 at 02:10

1 Answers1

1

in powershell, if you call a function with parens wrapped around comma delimited items, you get ONE OBJECT. [grin] your function is working and returning the array of three objects. the proper way to call that function with three inputs is thus ...

coalesce $Null 2 3

please also note that $nil is not $Null ... it's a new variable named nil with nothing in it - in other words, with the value of $Null in it.

Lee_Dailey
  • 7,292
  • 2
  • 22
  • 26