PowerShell中的全局变量和局部变量 [英] Global variables and local variables in PowerShell

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

问题描述

我有全局变量,想在函数中使用它们.

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"

推荐答案

在您的函数中,您正在修改哈希表的内容,因此除非您的函数(或函数与函数之间的函数调用者)全局范围)碰巧具有局部变量$ Var1和$ Var2(顺便说一句,您是否不错过$).如果这是您自己的代码,那么我会说保持原样.但是,如果您的代码允许其他人的代码调用您的函数,那么我将使用$global:Var1说明符来确保您正在访问全局变量,并且不会无意中访问正在调用的函数中的同名变量您的功能.

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.

关于PowerShell中动态作用域的另一件事是,当您为函数中的变量分配值时,该变量恰好是全局变量,例如:

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将对函数内的变量$ someGlobal进行写时复制"操作.如果您的意图是真正修改全局,则可以使用$global:说明符:

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天全站免登陆