Increment a variable in PowerShell in functions

You are running into a dynamic scoping issue. See about_scopes. Inside the function $incre is not defined so it is copied from the global scope. The global $incre is not modified. If you wish to modify it you can do the following.

$incre = 0

function comparethis() {
    #Do this comparison

    $global:incre++
    Write-Host $global:incre
}

comparethis #compare 2 variables
comparethis #compare 2 variables
comparethis #compare 2 variables
comparethis #compare 2 variables

Write-Host "This is the total $incre"

Rather than using a global variable I woul suggest to call the function with a reference to the variable:

[int]$incre = 0

function comparethis([ref]$incre) {
    $incre.value++;
}

comparethis([ref]$incre) #compare 2 variables
Write-Host $incre
comparethis([ref]$incre) #compare 2 variables
Write-Host $incre

If you want your counter to reset each time you execute the same script use $script scope:

$counter = 1;

function Next() {
    Write-Host $script:counter

    $script:counter++
}

Next # 1
Next # 2
Next # 3

With $global scope you will get 4 5 6 on the second script run, not 1 2 3.

Tags:

Powershell