在点源 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/