2016-08-20 69 views
0

我試圖更改ScriptBlock內的變量。 我在做什麼錯?在ScriptBlock中的PowerShell更改變量

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

輸出是0和1的重複序列。那麼如何訪問變量而不僅僅是它的副本呢?

+0

'$ count ++' - >'([ref] $ count).Value ++' – PetSerAl

+0

thansk,that worked。 – yogurtflute

回答

2

當您在ScriptBlock的範圍內修改$count時,會創建一個本地副本,並且原始範圍內的原始$Count變量保持不變。

有幾種方法在父範圍修改$count,無論是與一個明確的範圍限定:

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

或通過Get-Variable和相對-Scope參數(-Scope 1檢索變量是指直接父範圍內):

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

或(如pointed out by @PetSerAl),則使用關鍵字[ref]

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