Search code examples
powershelllocal-variables

Powershell local array re-initialization


I found an error in one of my scripts, it looks like PowerShell (version 2.0) does not re-initialize local arrays when entering a function again. Here is a minimalist example:

function PrintNumbersUntilX {
    param (
        [ Parameter( Mandatory = $true ) ] $X
    )
    $Number = 0
    while( $Number -le $X ) {
        Write-Host $Number
        $Number++
    }
}

function PrintNumbersUntilY {
    param (
        [ Parameter( Mandatory = $true ) ] $Y
    )
    $Number = ( , 0 )
    while( $Number[ 0 ] -le $Y ) {
        Write-Host $Number[ 0 ]
        $Number[ 0 ]++
    }
}

function Main {
    Write-Host 'X-3: '
    PrintNumbersUntilX -X 3
    Write-Host 'X-12: '
    PrintNumbersUntilX -X 12
    Write-Host 'Y-3: '
    PrintNumbersUntilY -Y 3
    Write-Host 'Y-12: '
    PrintNumbersUntilY -Y 12
}

Main

Output (linebreaks replaced with space):

X-3:  0 1 2 3 X-12:  0 1 2 3 4 5 6 7 8 9 10 11 12 Y-3:  0 1 2 3 Y-12:  4 5 6 7 8 9 10 11 12

PrintNumbersUntilX works as I would expect from a local variable but PrintNumbersUntilY does not reset (reinitialize) $Number

Is this bug fixed in later versions, or is this a 'feature', if so what is it called, and how can I get rid of it?


Solution

  • You can work around it in 2.0 by using an explicit array subexpression @() to initialize $Number:

    $Number = @( , 0 )