我敢肯定这是一个愚蠢的问题,但我似乎无法在函数中向数组添加元素。
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
$jobResult
后Gather-JobResults
为空,如何解决此问题?谢谢你的回答
最佳答案
这是一个范围问题,当您在函数中修改$ jobResult时,您并没有在此函数外部修改全局变量。
在函数内部使用$global:jobResult += ...
(或$ script:jobResult),应该可以
看看About_scope help page