4

My PowerShell script looks like this:

$counter = 1

function next() {
    Write-host "$counter"
    $counter++
}
next
next
next
next

What am I doing wrong? I want to see the counter increase.

The output, surprisingly (to me), looks like this:

1
1
1
1

3 Answers 3

5

Although, as the other answer suggests, you can change the scope of your variable to be $script:... or $global:...,

Any programmer will often say this is a bad idea. A global variable can have unexpected and really hard to troubleshoot problems and results. So instead, I'll tell you how to properly address the issue.

As you already figured out, variables inside a function don't go outside the function, but you can transport values in and out functions. Your code would become as follows:

function next() {
    param
    (
        $counter
    )

    Write-host "$counter"
    $counter++
    return ($counter)
}

$counter = 1

$counter = next -counter $counter
$counter = next -counter $counter
$counter = next -counter $counter
$counter = next -counter $counter
2

Make $Counter a reference variable:

[Ref]$Counter = 1

Function Next ()
{
    Write-Host ($Counter.Value++)
}
1

your $counter variable is scoped to the function only. Try using the global scope.

$global:counter = 1

function next() {
    Write-host "$global:counter"
    $global:counter++
}

see also: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.3

4
  • 2
    $global is a bad idea. At least use $script then. If another powershell script includes this script, it can affect the variable and cause weird issues. By using $script, you at least ensure that as the script runs, that variable is only changed by the execution of that script. $global is only useful for doing settings and stuff. Things that would be permanent.
    – LPChip
    Nov 23, 2022 at 20:58
  • @LPChip Well we don't know the full context of the question. There are plenty of valid uses of the global scope, as you said for settings.
    – paxamus
    Nov 23, 2022 at 21:01
  • 1
    In the code in the example, it is used as a way to change a value that resides inside a function. That is not a setting, so script is a much better option than global.
    – LPChip
    Nov 23, 2022 at 21:06
  • Thanks, I used $script instead. Nov 24, 2022 at 22:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .