Increment a variable in PowerShell in functions

powershell

Solution

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"

Problem

How do I increment a variable in a PowerShell function? I'm using the below example without any data to be input to the function. I want to increment a variable every time a function is called. The variable $incre has 1 added to it and then displays the total of $incre when the script completes. The total when running the below is 0, whereas the result I want is 4 as the function comparethis has been run 4 times and each time $incre has been incremented by 1. ``` $incre = 0 function comparethis() { # Do this comparison $incre++ Write-Host $incre } comparethis #compare 2 variables comparethis #compare 2 variables comparethis #compare 2 variables comparethis #compare 2 variables Write-Host "This is the total $incre" ```

Original source