点源变量 VS 全局变量 [英] Dot Sourced Variables VS Global Variables

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

问题描述

我有两种方法可以从单独的脚本文件中引用脚本变量.以下是两个基本示例:

1.点源
变量.ps1

$Source = "source"$Destination = "dest"

执行.ps1

<预><代码>..\变量.ps1Copy-Item -Path $Source -Destination $Destination -Force

2.全局变量
变量.ps1

$Global:Source = "source"$Global:Destination = "dest"

执行.ps1

.\Variables.ps1Copy-Item -Path $Source -Destination $Destination -Force

我已经做过研究,但还没有找到一个明确的理由来使用一个而不是另一个.使用这些方法时是否有限制或注意事项?非常感谢任何输入.感谢您抽出宝贵时间.

@mklement0 给出了一个很好的答案,说明为什么在全局变量上使用点源.我很想继续讨论这个问题.如果有其他观点,或者关于何时使用全局变量更有益的解释,我会很高兴听到它并相应地投票.谢谢.

解决方案

我建议你使用点源,没有显式的全局变量(方法一):>

那样,需要刻意努力将变量添加到当前范围.请注意,dot-sourcing 将变量添加到 current 作用域中,该作用域可能是也可能不是当前会话的 global 作用域(子作用域是通过调用脚本创建的(没有 dot-采购)和脚本块,例如 &).

相比之下,使用全局变量(方法 2)创建会话全局变量与调用方法无关,因此即使是意外的、非点源的脚本调用最终也会改变全局状态.

I have two ways of referencing script variables from a separate script file. Here are two basic examples:

1. Dot Source
Variables.ps1

$Source = "source"  
$Destination = "dest"

Execute.ps1

. .\Variables.ps1  
Copy-Item -Path $Source -Destination $Destination -Force

2. Global Variable
Variables.ps1

$Global:Source = "source"  
$Global:Destination = "dest"

Execute.ps1

.\Variables.ps1  
Copy-Item -Path $Source -Destination $Destination -Force

I have done research but have yet to find a definitive reason as to use one over the other. Are there limitations or cautions I should exercise when using these methods? Any input is greatly appreciated. Thank you for your time.

EDIT:

@mklement0 gave a great answer as to why to use dot-sourcing over global variables. I would love to still keep this discussion open. If there is another point of view, or an explanation as to when using global variables is more beneficial, I would enjoy hearing it and up-voting accordingly. Thank you.

解决方案

I suggest you use dot-sourcing, without explicit global variables (method 1):

That way, it requires a deliberate effort to add variables to the current scope. Note that dot-sourcing adds the variables to the current scope, which may or may not be the current session's global scope (child scopes are created by calling scripts (without dot-sourcing) and script blocks with &, for instance).

By contrast, using global variables (method 2) creates session-global variables irrespective of invocation method, so that even accidental, non-dot-sourced invocations of the script end up altering the global state.

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

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