PowerShell 变量冲突

标签 powershell

我有一个对我的大多数应用程序都通用的变量,称为“电子邮件”。我还想在其中一个脚本中使用“电子邮件”作为参数的名称。我需要在同一个脚本中引用两个变量的值。理想情况下,会有一种使用模块/命名空间或其他东西来引用的方法,也许有,但我不知道。你可以看到我是如何解决这个问题的,但它很丑而且容易出错。有没有更好的办法?

# PowerShell v1
# Some variable names are very common.
param ($emails)

# My Hack
# We need to save current value so we have it after we source in variables below.
$emails0=$emails

# Below is going to load a variable called "emails" which will overwrite parm above.
. C:\load_a_bunch_of_global_variables.ps1

最佳答案

这是因为正如文档所说:(点源运算符)运行一个脚本,以便脚本中的项目是调用范围的一部分。

在这种情况下,我会将 C:\load_a_bunch_of_global_variables.ps1 转换为模块并将 $emails 作为参数传递或导出设置 $script 的函数:emails 模块中的变量。那么这个变量就不会和父脚本中的变量发生冲突了。

有关模块的更多信息,您可以使用 get-help about_modules


如果可能的话,我会避免在我的脚本中使用全局变量。

为什么?因为这是一种代码味道(正如程序员所说)。一个脚本没有问题。如果两个脚本使用相同的全局变量并且只读取,这可能是可以接受的。但是,如果其中任何一个更改了值,则可能会出现不愉快的冲突。

在某些情况下 Get-Variable -scope 1 -name myvariable 会有所帮助,但我只会在封闭的代码片段(如模块)或短脚本中使用它(与使用全局变量的原因相同)。

关于PowerShell 变量冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2331825/

相关文章:

powershell - 如何使用脚本 block 和参数将 powershell.exe 与 -Command 一起使用

windows - 动力外壳 $?在做直到循环

powershell - 如何让 PowerShell 很好地处理文件名中的 [ 或 ] ?

sql - 有没有一种方法可以在Microsoft SQL Server中使用SQL Server Powershell搜索列?

powershell - 在 Powershell 中解析字符串

Powershell Active Directory - 将我的 get-aduser 搜索限制到特定 OU [和子 OU]

远程机器上的 Powershell Start-Process msiexec 不工作

powershell - 在构建期间在 AssemblyInfo 中设置 AssemblyCopyright、AssemblyCompany

powershell - 如何在powershell中分割文本文件中大于X的行?

powershell - 通过PowerShell从名称运行程序(类似于运行框)