在函数中增加PowerShell中的变量

时间:2023-01-30 00:38:25

How do I increment a variable in a PowerShell function. Im using the below example without any data to be input to the function. What I am wanting to achieve is 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, when the result I am wanting is 4 as the function comparethis has been run 4 times and each time $incre has been incremented by 1.

如何在PowerShell函数中增加变量。我使用以下示例,没有任何数据输入到该功能。我想要实现的是每次调用一个函数时增加一个变量,增量$ increment添加1,然后在脚本完成时显示$ increment的总和。运行下面的总数是0,当我想要的结果是4时,因为函数比较已经运行4次,每次$ increment增加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"

1 个解决方案

#1


19  

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.

您正在遇到动态范围问题。请参阅about_scopes。函数$ increment内部未定义,因此从全局范围复制。全局$ increment不会被修改。如果您想修改它,您可以执行以下操作。

$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"

#1


19  

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.

您正在遇到动态范围问题。请参阅about_scopes。函数$ increment内部未定义,因此从全局范围复制。全局$ increment不会被修改。如果您想修改它,您可以执行以下操作。

$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"