点源脚本时的 PowerShell 范围冲突

标签 powershell scope

在点源 powershell 脚本时,我遇到了一些范围问题。
假设我有一个脚本“A.ps1”:

$VERSION = "1.0"

# Dot source B.ps1
. .\B.ps1

function Write-Version { Write-Host "A.ps1 version $VERSION" }
Write-Version

还有一个脚本 B.ps1
$VERSION = "2.0"
function Write-Version { Write-Host "B.ps1 version $VERSION" }
Write-Version

运行 A.ps1 的输出将是:
B.ps1 version 2.0
A.ps1 version 2.0

为什么会发生这种情况很明显。 $VERSION B.ps1 中的变量被放入 A.ps1 的范围内并覆盖该变量。确实,这发生在 Write-Version 上。也一样,但是这里 A.ps1 覆盖了 B 的版本,但是因为 Write-Version在此之前在 B.ps1 中调用,我们仍然可以看到 B 的 Write-Version 函数的输出。

当然,问题是如何防止这种情况发生?我尝试了各种范围选项,但这在点源时似乎不起作用。而且由于 B.ps1 中有我在 A 的范围内确实需要的功能,因此仅调用 B.ps1 可能不是一种选择。

有没有人有任何想法?

最佳答案

您可以通过将 B.ps1 设为模块并将其重命名为 B.psm1 来实现。添加 Export-ModuleMember使您的函数可用于其他脚本。

这将是 B.psm1:

$VERSION = "2.0"
function Write-Version { Write-Host "B.ps1 version $VERSION" }
Write-Version

# Only items specified here will be exported. If Export-ModuleMember is not used,
# ALL members (functions, variables, and aliases) will be exported. In this case
# if $VERSION was exported, $VERSION will be set to "2.0" in script A.ps1
Export-ModuleMember -Function Write-Version

A.ps1 将是:
$VERSION = "1.0"

# Import B.psm1
Import-Module .\B.psm1

function Write-Version { Write-Host "A.ps1 version $VERSION" }
Write-Version

# Use B.psm1's `Write-Version` function
B\Write-Version

关于点源脚本时的 PowerShell 范围冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8521005/

相关文章:

arrays - 如何使用数组作为参数?

powershell - 如何获取正在执行 Azure 自动化 Runbook 的用户 ID

ruby-on-rails - 具有 where 和 where.not 的命名范围

unit-testing - Pester:并非所有模拟函数都被拦截

c# - 在 PowerShell 上通过 Rest 获取自定义对象

JavaScript 声明的全局变量无法在方法中赋值

javascript - 如何在父作用域获取静态数据后在子作用域中运行函数

javascript - 如果变量尚未传递给函数,则初始化该变量。这是正确的方法吗?

c - #define 变量的范围是什么?

powershell - 并行化 powershell 脚本执行