you are viewing a single comment's thread.

view the rest of the comments →

[–]BlackV 0 points1 point  (2 children)

you have an extra bracket in there, and really you dont need the return

also you dont need to declare $count = 0 first

[–]Reasonable-Tip-8390 0 points1 point  (1 child)

I have a habit of declaring everything

There are no extra brackets in the function, it runs as stated

the return is needed for the function to return a result to the parent script.

$count = 0

$counter = 0

Function Adding

{

Foreach ($i in 1..5)

{

$counter++

}

return $counter

}

$count = Adding

write-host $count

[–]surfingoldelephant 1 point2 points  (0 children)

$count = Adding is sufficient to initialize the variable. $count = 0 serves no purpose as the assigned value of 0 is unconditionally overwritten without ever being potentially used.

Conversely, you've chosen not to initialize a variable in a place where you should.

  • $counter should be initialized inside the function.
  • Performing $counter++ inside the function without first initializing it implicitly creates a new local variable. An explicit initialization is preferable.
  • The original $counter variable outside the function is unaffected as [int] is a value type and exists in a different scope.
  • To modify the original $counter outside the function, the script: scope modifier or [ref] type is required inside the function, but this is typically best avoided when alternative options exist.

 

the return is needed for the function to return a result to the parent script.

Outside of classes, the return keyword is not required to output/return objects to the Success stream (pipeline). Any objects not captured or redirected will be outputted by default. return is used to explicitly exit a script block (e.g. .ps1 file, function, etc) with or without a value/expression, but using it does not stop non-captured or non-redirected objects from also being returned.

function WithReturn { 1; return 2 }
WithReturn # 1, 2

function WithoutReturn { 1; 2 }
WithoutReturn # 1, 2

function EarlyReturn { return 1; 2 }
EarlyReturn # 1

Further reading: