Tuesday, February 15, 2011

Watching PS Vars for changes - Events

I have a Testing framework built around Powershell and .net. In the framework there are a couple of main objects that their property values are assigned to Globals that are well know and used. The problem was I did not want to make them read only as this causes issues if reloading the framework and or trying to change paths. I needed a way to report back the value of a variable if it changes so i could keep the objects in sync. First I used Set-PSBreakPoint –Action to Check the value but it breaks before the value is set. Then I thought I need an Event but Powershell has limited native events. So I just started tweeting and thanks to @oising I finally have a solution. Here is a simple example that can be built upon.

 

#Set value to a new variable
$n = 0

#set A break point to watch for any write actions to that variable
#this will fire a new event VariableChanged
$BP = Set-PSBreakpoint -Variable n -Mode Write -Action {
New-Event -SourceIdentifier VariableChanged
}

#Now register to recieve the VariableChanged events
#Here we just check the value of our variable and get its new value
$EE = Register-EngineEvent -SourceIdentifier VariableChanged -Action {
Write-Host $n -ForegroundColor Yellow
}

#assign a new value to n and see the vent fires
$n = 1

#do some cleanup
Get-PSBreakpoint | Remove-PSBreakpoint
Get-EventSubscriber | Unregister-Event -Force
Get-Event | Remove-Event


 



Good-Times | Get-Command –:)

No comments:

Post a Comment