Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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

share|improve this answer
    
Thanks a lot, it work now :) i will check this help page. Have a nice day. –  Zabaa Sep 10 '13 at 13:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.