1

I'm sure it's a silly problem but I can't seem to add element to array in function.

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

The $jobResult is empty after I call 3x Gather-JobResults, how can I fix this ?

Thanks for any answers

1 Answer 1

4

this is a scope problem, when you modify $jobResult in your function , you're not modifying the global variable defined outside this function.

inside your function use $global:jobResult += ... (or $script:jobResult) and it should be ok

look at the About_scope help page

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.