PowerShell: Break, Return Or Exit?

Question

What is the difference between the keywords Exit, Return and Break in PowerShell?
What does each exactly do?

Short Answer

  • Break terminates execution of a loop or switch statement and hands over control to next statement after it.
  • Return terminates execution of the current function and passes control to the statement immediately after the function call.
  • Exit terminates the current execution session altogether. It also closes the console window and may or may not close ISE depending on what direction the wind is facing.

Not sure I get it yet…
Can you provide some examples?

Sure thing, let’s look at an example for each one.

Continue reading “PowerShell: Break, Return Or Exit?”

Advertisements

How To Easily Loop And Index In PowerShell

Just learned these bits today while trying to answer something and thought to share them.

Consider these two arrays:

$x = @("a","b","c","d");
$y = @("apple","banana","carrot","dinner");

What I want to see as output is:

a is for apple
b is for banana
c is for carrot
d is for dinner

There are a couple of ways of going about this and then some.

You can use a regular for loop:

for ($i = 0; $i -Lt $x.Count; ++$i)
{
    "$($x[$i]) is for $($y[$i])";
}

You can go with a regular foreach loop too this way, if the values in $x are distinct – we’ll get around that in a second:

foreach ($v in $x)
{
    "$v is for $($y[$x.IndexOf($v)])"
}

You can shorten it by using a ForEach-Object CmdLet:

$x | ForEach-Object { "$_ is for $($y[$x.IndexOf($_)])" };

You can shorten the ForEach-Object into the % operator:

$x | % { "$_ is for $($y[$x.IndexOf($_)])" };

And finally, you can fix the issue of indexing duplicates by adding an initializer to the foreach and treating it just like a for:

$x | % { $i = 0 } { "$_ is for $($y[$i])"; ++$i };

You learn something new every day.


Index: PowerShell HowTo’s