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

joo*_*p s 4 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 
Run Code Online (Sandbox Code Playgroud)

我的变量$c是全局可访问的,但在所有情况下都不是常量.尝试更改函数内部的值test(),PowerShell允许更改值.

有没有办法创建一个真正的全局常量变量?

背景:

我有一个主要的脚本.主脚本加载了几个模块.通过所有模块和主脚本,我需要一些固定的文件和注册表路径.所以我想将这些路径声明为全局常量.

Ans*_*ers 9

全局变量$c保持不变,但分配$c = "xxxx"另一个本地变量$c定义,是以新的价值,掩盖了当地环境的全局变量.

示范:

PS C:\> Set-Variable -Name c -Value "x" -Option Constant -Scope Global -Force
PS C:\> function test {
>>     Get-Variable -Name c -Scope Global
>>     Get-Variable -Name c -Scope Local
>>     $c = "xxxx"
>>     Get-Variable -Name c -Scope Global
>>     Get-Variable -Name c -Scope Local
>> }
>>
PS C:\> test

Name                           Value
----                           -----
c                              x
Get-Variable : Cannot find a variable with the name 'c'.
At line:3 char:5
+     Get-Variable -Name c -Scope Local
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (c:String) [Get-Variable], ItemNotFoundException
    + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand

c                              x
c                              xxxx

第一次Get-Variable -Name c -Scope Local调用失败,因为$c尚未定义局部变量.

通过在变量/常量前加上正确的范围来避免这个问题:

PS C:\> Set-Variable -Name c -Value "x" -Option Constant -Scope Global -Force
PS C:\> function test {
>>     $global:c
>>     $global:c = "xxxx"
>>     $global:c
>> }
>>
PS C:\> test
x
Cannot overwrite variable c because it is read-only or constant.
At line:3 char:5
+     $global:c = "xxxx"
+     ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (c:String) [], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable

x

或者通过为所有范围定义常量:

PS C:\> Set-Variable -Name c -Value "x" -Option Constant, AllScope -Force
PS C:\> function test {
>>     $c
>>     $c = "xxxx"
>>     $c
>> }
>>
PS C:\> test
x
Cannot overwrite variable c because it is read-only or constant.
At line:3 char:5
+     $c = "xxxx"
+     ~~~~~~~~~~~
    + CategoryInfo          : WriteError: (c:String) [], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable

x