yogurtflute yogurtflute - 2 months ago 5x
PowerShell Question

PowerShell Change Variable in ScriptBlock

I'm trying to change a variable inside a ScriptBlock.
What am I doing wrong?

$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window.Add_SourceInitialized( {
$timer = new-object System.Windows.Threading.DispatcherTimer
$timer.Interval = [TimeSpan]"0:0:0.25"
$timer.Add_Tick( $updateBlock )
} )
$count = 0
$updateBlock = { Write-Host $count; $count++; Write-Host $count}

The Output is a repeating sequence of 0 and 1. So how do I access the variable and not only a copy of it?


When you modify $count inside the scope of the ScriptBlock, a local copy is created, and the original $Count variable in the parent scope is left untouched.

There are a few ways to modify $count in the parent scope, either with an explicit scope qualifier:

$updateBlock = { Write-Host $count; $script:count++; Write-Host $count}

Or by retrieving the variable with Get-Variable and the relative -Scope parameter (-Scope 1 refers to the immediate parent scope):

$updateBlock = { Write-Host $count; (Get-Variable -Scope 1 -Name count).Value++; Write-Host $count}

Or (as pointed out by @PetSerAl), use the [ref] keyword:

 $updateBlock = { Write-Host $count; ([ref]$count).Value++; Write-Host $count}