【问题标题】:Global array, feed from a function does not preserve content [duplicate]全局数组,来自函数的提要不保留内容[重复]
【发布时间】:2021-06-02 16:11:22
【问题描述】:

我有一个调用本地函数的数据循环。

在这个函数中,我提供了一个全局范围的数组。

但是,最后,数组是空的。为什么 ?以及如何解决?

要重现该行为,请尝试以下操作:

$myArray = @() # Global array

function Invoke-SomeAction{
    param(
        [Parameter()]
        [int]$Val
    )

    $myArray += $Val
}

1..10 | % {

    Invoke-SomeAction -Val $_

}

$myArray.Count # Expect 10, got 0

如果我像这样删除函数调用:

$myArray = @() # Global array

1..10 | % {

    $myArray += $_

}

$myArray.Count # Expect 10, got 10

它的行为符合预期。

PS:如果重要的话,这是我的$PSVersionTable

Name                           Value                                                                                                                           
----                           -----                                                                                                                           
PSVersion                      5.1.14393.3053                                                                                                                  
PSEdition                      Desktop                                                                                                                         
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                         
BuildVersion                   10.0.14393.3053                                                                                                                 
CLRVersion                     4.0.30319.42000                                                                                                                 
WSManStackVersion              3.0                                                                                                                             
PSRemotingProtocolVersion      2.3                                                                                                                             
SerializationVersion           1.1.0.1            

【问题讨论】:

    标签: powershell


    【解决方案1】:

    原因是作用域不同。您正在尝试在函数范围内添加到 $myArray,但您需要在脚本范围内添加。试试这个:

    $myArray = @() # Global array
    
    function Invoke-SomeAction{
        param(
            [Parameter()]
            [int]$Val
        )
    #this sets a variable scope to script 
        $script:myArray += $Val
    }
    
    1..10 | % {
    
        Invoke-SomeAction -Val $_
    
    }
    
    $myArray.Count
    

    在此处了解更多信息:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-11
      • 2021-06-10
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      相关资源
      最近更新 更多