Unexpected PowerShell Closures and Controlling the Flow of PowerShell Scripts

Problem scenario:  You PowerShell or PowerCLI window keeps exiting automatically when you run a script.  You find that RAM and CPU are not constrained.  
Root cause: Human error.
Solution:  Look for the "exit" or the "Exit-Pssession" commands.  These can close PowerShell's ISE or PowerCLI.  You may need to eliminate these commands or use a different keyword.

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Problem scenario:  You want to use a for-each loop in PowerShell, you do not want the script to cause the interactive PowerShell window to close, and you want the action portion (in braces {}) to run only once.  What do you do if you do not want to re-write the function to use an "if" or a "while" loop?

Solution:  Use the "break" or "return" key word as the last line in the action clause.

foreach ($cont in $integration) {
   write-host $cont
   return  # or break
}

Return will return the control of the PowerShell interpreter to the previous location before entering the foreach loop.  This is particularly significant when you have functions.  Break can be called with an accompanying label.  For example,
this code would not just interrupt the foreach clause but the PowerShell interpreter would start parsing the ":contInt" section of code:

:contInt if ($foo -eq 289) {
     while ($foo < 505) {
        foreach ($cont in $integration) {
           write-host $cont
           Break :contInt    
         }
      }
}

In the future we want to re-write these directions to use write-verbose instead of write-host. We want to warn people that write-verbose is recommended instead of write-host (according to this posting).

Leave a comment

Your email address will not be published. Required fields are marked *