PowerShell全局变量局部变量 [英] PowerShell Global variables local variables

查看:1290
本文介绍了PowerShell全局变量局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有全局变量,并希望在函数中使用它们。



我不在函数中使用同名的局部变量!

 #global vars:
$ Var1 = @ {。 。}
$ Var2 = @(..)
函数测试{
$ Var1.keyX =kjhkjh
$ Var2 [2] = 6.89768
}

我这样做,它可以工作,但它是安全的还是必须使用:

  $ Global:Var1.keyX =kjhkjh

感谢,
Gooly

解决方案

函数,你正在修改哈希表的内容,所以不需要使用$ global,除非你的函数(或函数和全局作用域之间的函数调用者)碰巧有局部变量$ Var1和$ Var2(顺便说一句,你不是你缺少 $ )。如果这是你自己的代码,那么我会说,保持原样。但是,如果您的代码允许其他人的代码调用您的函数,那么我将使用 $ global:Var1 说明符来确保您正在访问全局变量而不是在调用函数的函数中无意中访问了一个名称相同的变量。



另一个需要了解PowerShell动态范围的知识是,当您为变量赋值时在一个函数中,这个变量碰巧是一个全局变量,例如:

pre $ g $ g $ g $ g $ f $ {$ someGlobal = 42; $ someGlobal}
foo
$ someGlobal

PowerShell将执行写入操作变量$ someGlobal中的函数。如果你的意图是要真正修改全局,那么你可以使用 $ global:说明符:

  $ someGlobal = 7 
函数foo {$ global:someGlobal = 42; $ someGlobal}
foo
$ someGlobal


I have global variables and want to use them with in a function.

I don't use local variables with the same name within the functions!

# global vars:
$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:

$Global:Var1.keyX = "kjhkjh"

Thanks, Gooly

解决方案

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

这篇关于PowerShell全局变量局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆