PowerShell: Goodbye, Goto

When batch files were added to MS-DOS over 30 years ago, the BASIC programming language was the predominant programming language in use on microcomputers. The BASIC language used the GOTO statement to provide the programmer the ability to repeat lines of code, so Microsoft added the Goto command to the batch file “language” to provide the same type of functionality. Listing 1 shows a simple batch file that illustrates the Goto command that jumps to batch label to repeat the Echo command 5 times.

                              
@Echo Off

Set NUM=5

:REPEAT

Echo %NUM%

Set /A NUM-=1

If %NUM% GTR 0 Goto :REPEAT

Set NUM=

Listing 1: Batch file Goto example

 

When the batch file “language” was updated in Cmd.exe on the Windows NT platform, Microsoft enhanced the Call command to allow a label in a batch file to act as a simple subroutine, similar to the old BASIC GOSUB statement. Listing 2 shows an example of this use of the Call command.

                              
@Echo Off

Call :SAYHELLO Ken

Echo End of batch file

Goto :END

:SAYHELLO

Echo Hello, %1

:END

Listing 2: Batch file with a subroutine

 

When you run the batch file in Listing 2, it outputs “Hello, Ken” and then “End of batch file.” The Call command causes execution to jump to the command after the label, and then execution returns to the line after the Call command. Also, batch file subroutines have no built-in way to return values without relying on environment variables and unintuitive Cmd.exe parsing quirks.

 

The point is that while the batch file Goto and Call commands both provide the ability to repeat lines of code, they do so in an unstructured manner. That is, a Goto or Call command can arbitrarily jump to any label in the batch file. As the batch file gets more complex, the use of Goto and/or Call eventually leads to what we call “spaghetti code” because the batch file’s logic gets harder and harder to follow.

 

PowerShell’s authors have bypassed the “spaghetti code” problem entirely. PowerShell has neither a Goto command nor a Call command, because it doesn’t need them. Instead, PowerShell has structured programming statements that replace both Goto (for iteration) and Call (for subroutines).

PowerShell Iteration

Iteration, or looping, refers to repeating code. PowerShell has four basic language statements that repeat lines of code based on a condition: while, do while, do until, and for. These four language statements, or looping constructs, effectively eliminate the need for the Goto command.