powershell - 如何在 PowerShell 中创建全局常量变量

标签 powershell constants

## 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/

相关文章:

powershell - 启动进程重定向输出到$ null

const unsigned char[][] 的 C 数组

c++ - C++中的比较

enums - 使用枚举的节俭常量结构

windows - PowerShell [wmiclass] Win32_Process.Create() 然后等待批处理文件完成

c# - 如何使用 C# 验证 PowerShell 脚本是否正在运行

swift - 常量属性可以在初始化期间修改吗?修改的?什么?

c++ - "const T*"可以匹配指向自由函数的指针吗?

windows - 如何让AppVeyor使用不同版本的Emacs?

azure - 如何修复 AzureADPreview Windows PowerShell 中的 'Policy operations on v2 application are disabled'