arrays - 在函数中向数组添加元素,但数组仍为空

标签 arrays function powershell powershell-2.0

我敢肯定这是一个愚蠢的问题,但我似乎无法在函数中向数组添加元素。

PowerShell 2.0

$jobResult = @()

function Gather-JobResults {
    Param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string] $message
    )
    begin {}
    process {
        $jobResult += ([string]::Format("{0} - {1}", (Get-Date -f "yyyy-MM-dd HH:mm:ss"), $message))
        Write-Host "--- Status jobResult ---> $jobResult"
    }
    end{}
}

Gather-JobResults("zabaaa")
Gather-JobResults("zaaaauuuuuuuul")
Gather-JobResults("winkoooo")

$jobResult

调用3x $jobResultGather-JobResults为空,如何解决此问题?

谢谢你的回答

最佳答案

这是一个范围问题,当您在函数中修改$ jobResult时,您并没有在此函数外部修改全局变量。

在函数内部使用$global:jobResult += ...(或$ script:jobResult),应该可以

看看About_scope help page

关于arrays - 在函数中向数组添加元素,但数组仍为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18719747/

相关文章:

python - 替换数组中值的最快方法

c++函数在f()+ g()中的调用顺序

c++ - 在类内部而不是在 C++ 外部定义成员函数?

c - 如何使用 O(n) 算法在 C 中就地分区数组?

javascript - 如何比较嵌套数组中的元素

c - 我如何摆脱调用 __x86.get_pc_thunk.ax

powershell - 将路径管道传递到测试路径时,PowerShell ISE “Illegal characters in path”?

json - Powershell Invoke-RestMethod返回JSON

powershell - 将字符串分成单独的字符串/列

javascript动态填充关联数组并获取值