David F. Severski
David F. Severski

Reputation: 493

Module scoped variables being changed without explicit assignment

I'm quite confused with some variable scoping behavior I'm experiencing. Take the following sample module:

$script:intTemplate = 1

[xml]$script:xmlTemplate = @"
<test>
    <element>
    </element>
</test>
"@

function getvar {
    $myint = $script:intTemplate
    $myint++
    Write-output "Myint is $myint while intTemplate is $intTemplate"

    $myxml = $script:xmlTemplate
    $e = $myxml.CreateElement("MyChildElement")
    $myxml.SelectSingleNode("/test").AppendChild($e) |Out-Null
    $myxml.Innerxml.tostring()
    $script:xmltemplate.Innerxml.tostring()
}    

Now importing that module are running getvar generates:

PS C:\Windows\system32> getvar
Myint is 2 while intTemplate is 1
<test><element></element><MyChildElement /></test>
<test><element></element><MyChildElement /></test>

Further runs of getvar continue to add more and more child elements to $xmlTemplate while $intTemplate remains the same. I don't understand why $myXml is not always starting off with the simple test/element structure and, more to the point, how the script local $xmlTemplate variable appears to be getting changed while intTemplate does not.

Any assistance on figuring out what is going on here would be much appreciated.

David

Upvotes: 2

Views: 86

Answers (1)

JPBlanc
JPBlanc

Reputation: 72640

As far as I understand scope has nothing to do with you problem, when you write $myInt=$script:intTemplate you manipulate a value, so you copy the value. When you write $myxml = $script:xmlTemplate you manipulate a reference, so copying a reference, you work with the same underlying object. Just try $script:intTemplate += 1.

Upvotes: 1

Related Questions