PowerShell Global variables local variables -
i have global variables , want utilize them in function.
i don't utilize local variables same name within functions!
class="lang-powershell prettyprint-override"># global vars: $var1 = @{ .. } $var2 = @( .. ) function testing{ $var1.keyx = "kjhkjh" $var2[2] = 6.89768 }
i , works, safe or have use:
class="lang-powershell prettyprint-override">$global:var1.keyx = "kjhkjh"
thanks, gooly
in function, modifying contents of hashtable there no need utilize $global unless function (or function caller between function , global scope) happens have local variables $var1 , $var2 (btw aren't missing $
). if own code i'd leave is. however, if code allows other folks' code phone call function, utilize $global:var1
specifier create sure you're accessing global variable , not inadvertently accessing variable of same name within function calling function.
another thing know dynamic scoping in powershell when assign value variable in function , variable happens global e.g.:
$someglobal = 7 function foo { $someglobal = 42; $someglobal } foo $someglobal
powershell "copy-on-write" operation on variable $someglobal within function. if intent modify global utilize $global:
specifier:
$someglobal = 7 function foo { $global:someglobal = 42; $someglobal } foo $someglobal
powershell global-variables
No comments:
Post a Comment