问题
I have global variables and want to use them within a function.
I don't use local variables with the same name within the functions!
# Global variables:
$Var1 = @{ .. }
$Var2 = @( .. )
function testing{
$Var1.keyX = "kjhkjh"
$Var2[2] = 6.89768
}
I do it and it works, but is it safe or do I have to use the following?
$Global:Var1.keyX = "kjhkjh"
回答1:
In your function, you are modifying the contents of the hashtable so there is no need to use $global unless your function (or a function caller between your function and global scope) happens to have local variables $Var1 and $Var2 (BTW aren't you missing $
). If this is all your own code then I'd say leave it as is. However, if you code allows other folks' code to call your function, then I would use the $global:Var1
specifier to make sure you're accessing the global variable and not inadvertently accessing a variable of the same name within a function that is calling your function.
Another thing to know about dynamic scoping in PowerShell is that when you assign a value to variable in a function and that variable happens to be a global e.g.:
$someGlobal = 7
function foo { $someGlobal = 42; $someGlobal }
foo
$someGlobal
PowerShell will do a "copy-on-write" operation on the variable $someGlobal within the function. If your intent was to really modify the global then you would use the $global:
specifier:
$someGlobal = 7
function foo { $global:someGlobal = 42; $someGlobal }
foo
$someGlobal
来源:https://stackoverflow.com/questions/24435745/global-variables-and-local-variables-in-powershell