hello.
please me understand scoping in case of powershell objects. here sample script:
##################################
########## begin script ##########
$global:obj = new-object psobject
add-member -inputobject $obj -membertype noteproperty -name "var" -value "object value"
[string]$global:str = "string value"
function setnewvalues {
"in setnewvalues before change `$obj.var = '{0}'" -f $obj.var
"in setnewvalues before change `$str = '{0}'" -f $str
$obj.var = "new object value"
$str = "new string value"
"in setnewvalues after change `$obj.var = '{0}'" -f $obj.var
"in setnewvalues after change `$str = '{0}'" -f $str
}
"before setnewvalues `$obj.var = '{0}'" -f $obj.var
"before setnewvalues `$str = '{0}'" -f $str
setnewvalues
"after setnewvalues `$obj.var = '{0}'" -f $obj.var
"after setnewvalues `$str = '{0}'" -f $str
########### end script ###########
##################################
and here script output:
#########################################
########## begin script output ##########
before setnewvalues $obj.var = 'object value'
before setnewvalues $str = 'string value'
in setnewvalues before change $obj.var = 'object value'
in setnewvalues before change $str = 'string value'
in setnewvalues after change $obj.var = 'new object value'
in setnewvalues after change $str = 'new string value'
after setnewvalues $obj.var = 'new object value'
after setnewvalues $str = 'string value'
########### end script output ###########
#########################################
so see not necessary specify scope modifier objects explicitly.
it looks default scope object scope in created. correct?
i want know, if following assertion objects psobject true: powershell use object highest parent scope, if there 1 object given name in scopes. , in case don't need specify scope explicitly.
in case of "simple" objects (like strings) not true, because powershell create new variable in child scope implicitly. please see example script , it's result - when function completed variable $str in parent (global) scope remains untouched. property $obj.var changed, although change them both without $global: scope modifier.
Comments
Post a Comment