## My try to create a global constant
Set-Variable -Name c -Value "x" -Option Constant -Scope Global -Force
Write-Host $c ## -> x
$c = "y" ## -> WriteError: (C:String) [], SessionStateUnauthorizedAccessException
## -> VariableNotWritable
Write-Host $c ## -> x
function test {
Write-Host $c ## -> x
$c = "xxxx"
Write-Host $c ## -> xxxx
}
test
我的变量
$c
是全局可访问的,但并非在所有情况下都保持不变。尝试更改函数内的值test()
PowerShell 允许更改值。有没有办法创建一个真正的全局常量变量?
背景:
我有一个主脚本。主脚本加载了几个模块。通过所有模块和主脚本,我需要一些固定的文件和注册表路径。
所以我想将这些路径声明为全局常量。
最佳答案
完整答案:
#________________________________________________
# Example1, without prefix
#________________________________________________
$c="val1"
# Print output c variable
$c
function test
{
$c="val2"
}
test
# Print output c variable (c not change)
$c
#________________________________________________
# Example2, with prefix global
#________________________________________________
$global:c="val1"
# Print output c variable
$global:c
function test2
{
$global:c="val2"
}
test2
# Print output c variable (c change)
$global:c
#________________________________________________
# Example3, with prefix script
#________________________________________________
$script:c="val1"
# Print output c variable
$script:c
function test3
{
$script:c="val2"
}
test3
# Print output c variable (c change)
$script:c
#________________________________________________
# Example 4, with get and set variable --> see answer of Ansgar Wiechers
#________________________________________________
注意:全局和脚本的差异是一个范围问题。更多详情,请参阅 here .
关于powershell - 如何在 PowerShell 中创建全局常量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47116729/