如何在 Powershell 中增加函数中的值?

Joh*_*man 4 powershell

我的 PowerShell 脚本如下所示:

$counter = 1

function next() {
    Write-host "$counter"
    $counter++
}
next
next
next
next
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我想看到计数器增加。

令人惊讶的是(对我来说),输出看起来像这样:

1
1
1
1
Run Code Online (Sandbox Code Playgroud)

LPC*_*hip 5

虽然,正如另一个答案所建议的,您可以将变量的范围更改为 $script:... 或 $global:...,

任何程序员都会经常说这是一个坏主意。全局变量可能会产生意想不到的且很难解决的问题和结果。因此,我将告诉您如何正确解决该问题。

正如您已经发现的,函数内部的变量不会传到函数外部,但您可以将值传入和传出函数。你的代码将变成如下:

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
Run Code Online (Sandbox Code Playgroud)