2

I have a function like this in Powershell:

function F()
{
      $something | Foreach-Object {
           if ($_ -eq "foo"){
                #  Exit from F here
           }
      }
      # do other stuff
}

if I use Exit in the if statement, it exits powershell, I don't want this behavior. If I use return in the if statement, foreach keeps executing and the rest of the function is also executed. I came up with this:

function F()
{
      $failed = $false
      $something | Foreach-Object {
           if ($_ -eq "foo"){
                $failed = $true
                break
           }
      }
      if ($failed){
          return
      }

      # do other stuff
}

I basically introduced a sentinel variable holding if I broke out of the loop or not. Is there a cleaner solution?

ahmet alp balkan
  • 42,679
  • 38
  • 138
  • 214
  • 2
    Depending on what `$something` is, you could use the `foreach` statement instead of the `Foreach-Object` cmdlet and use `return`... – DarkAjax Jul 23 '14 at 22:31

2 Answers2

0

Any help?

function F()
{
  Trap { Return }
  $something |
    Foreach-Object {
     if ($_ -eq "foo"){ Throw }
     else {$_}
    }
  }

 $something = "a","b","c","foo","d","e"   

 F
 'Do other stuff'
a
b
c
Do other stuff
mjolinor
  • 66,130
  • 7
  • 114
  • 135
0

I'm not entirely sure of your specific requirements, but I think you can simplify this by looking at it a different way. It looks like you just want to know if any $something == "foo" in which case this would make things a lot easier:

if($something ? {$_ -eq 'foo')) { return }

? is an alias for Where-Object. The downside to this is that it will iterate over every item in the array even after finding a match, so...

If you're indeed searching a string array, things can get even simpler:

if($something -Contains 'foo') { return }

If the array is more costly to iterate over, you might consider implementing an equivalent of the LINQ "Any" extension method in Powershell which would allow you to do:

if($something | Test-Any {$_ -eq 'foo'}) { return }

As an aside, while exceptions in the CLR aren't that costly, using them to direct procedural flow is an anti-pattern as it can lead to code that's hard to follow, or, put formally, it violates the principal of least surprise.

Community
  • 1
  • 1
Fred
  • 1,292
  • 10
  • 24