Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

ScriptProperty and scope issues

$
0
0

Hello all.  I have what seems to be an odd problem to me.  I'm noticing that if I return a PsObject from a function, the members that are ScriptProperties don't seem to hold their value outside of the function.  For example, I have an xml file similar to this:

 

<Actions>

      <Action>

            <Name>Testing</Name>

            <Site>Development</Site>

      </Action>

      <Action>

            <Name>Testing Two</Name>

            <Site>QA</Site>

      </Action>

</Actions>

 

Then I have a function similar to:

 

function ObjectTest

{

     $Obj = New-Object PsObject -Property @{ Name = "Whatever" }

     $Xml = [xml](cat C:\Xml.xml)

     $Obj | Add-Member -MemberType ScriptProperty -Name Actions -Value { $Xml.Actions.Action | ?{ $_.Name -eq "Testing" | select -Expand Site }}

 

     #If I check $Obj.Actions here, it has the correct value of 'Development'

     $Obj

}

 

$MyObj = ObjectTest

 

#This next line returns 'Development' and 'QA' in an array instead of just 'Development'

$MyObj.Actions

 

So inside the function, the ScriptProperty has the correct single value.  Outside of the function, it contains multiple values, as if it's ignoring the where clause inside the Add-Member scriptblock.

 

I've noticed this behavior in other situations with ScriptProperties too, but have never taken the time to dig into it. In those other situations, I just switched the member type to something other than ScriptProperty, and it would instantly start behaving as I'd expect, but that's really not an option this time.  

 

Can anyone explain to me what's going on with ScriptProperties and scope?  I appreciate it.

 

Thanks,


Viewing all articles
Browse latest Browse all 6937

Trending Articles