I'm trying to use a higher-order function to perform a certain task, but it seems that the scope isn't working as I expected. The code is as follows:
function DoSomething($scriptBlock, $message) {
# if not only running a check, run the given code
if ($shouldRunCheck) {
return $scriptBlock.Invoke()
}
Write-Host $message -foreground cyan
# write $message to file
}
This seems to work fine, but when I call it I don't seem to be able to save to variables outside of the script block.
$myArray = @()
$myArray += 'test 1'
DoSomething {
write-host $myArray # test 1
$myArray += 'test 2'
write-host $myArray # test 2
}
write-host $myArray # test 1
$myArray += 'test 3'
write-host $myArray # test 1 test 3
Essentially I'm need to add to the array variable from within the callback function but it just seems to over-write the variable as if the variable is read only?