点源变量 VS 全局变量

编程入门 行业动态 更新时间:2024-10-26 09:19:16
本文介绍了点源变量 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 全局变量

本文发布于:2023-07-05 06:51:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   全局变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!