PowerShell支持常量吗?

Tom*_*zel 106 powershell constants

我想在PowerShell中声明一些整数常量.

有没有好办法呢?

Mot*_*rom 107

使用

Set-Variable test -option Constant -value 100
Run Code Online (Sandbox Code Playgroud)

要么

Set-Variable test -option ReadOnly -value 100
Run Code Online (Sandbox Code Playgroud)

"常量"和"只读"之间的区别在于可以通过以下方式删除(然后重新创建)只读变量

Remove-Variable test -Force
Run Code Online (Sandbox Code Playgroud)

而不能删除常量变量(即使使用-Force).

有关更多详细信息,请参阅此TechNet文章.

  • @masi只强制值`Set-Variable test -option Constant -value [string] 100` (8认同)
  • @Monso指定类型如`([string] 100)`时,你需要围绕值括号.见下面的答案. (7认同)
  • 嗯,但**在使用`Set-Variable`时如何强制数据类型**?处理变量时,可以使用`[string] $ name = value`,但这似乎不可能用于常量? (4认同)

rob*_*rob 13

这是一个定义常量的解决方案:

const myConst = 42
Run Code Online (Sandbox Code Playgroud)

解决方案取自http://poshcode.org/4063

    function Set-Constant {
  <#
    .SYNOPSIS
        Creates constants.
    .DESCRIPTION
        This function can help you to create constants so easy as it possible.
        It works as keyword 'const' as such as in C#.
    .EXAMPLE
        PS C:\> Set-Constant a = 10
        PS C:\> $a += 13

        There is a integer constant declaration, so the second line return
        error.
    .EXAMPLE
        PS C:\> const str = "this is a constant string"

        You also can use word 'const' for constant declaration. There is a
        string constant named '$str' in this example.
    .LINK
        Set-Variable
        About_Functions_Advanced_Parameters
  #>
  [CmdletBinding()]
  param(
    [Parameter(Mandatory=$true, Position=0)]
    [string][ValidateNotNullOrEmpty()]$Name,

    [Parameter(Mandatory=$true, Position=1)]
    [char][ValidateSet("=")]$Link,

    [Parameter(Mandatory=$true, Position=2)]
    [object][ValidateNotNullOrEmpty()]$Mean,

    [Parameter(Mandatory=$false)]
    [string]$Surround = "script"
  )

  Set-Variable -n $name -val $mean -opt Constant -s $surround
}

Set-Alias const Set-Constant
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,当模块中包含“Set-Constant”时,这不起作用。它将在模块范围内创建一个常量,其中包含“Set-Constant”。作为一种解决方法,可以传递参数“-Surround Global”,但这并不总是需要的。我想在另一个模块或本地函数中创建一个常量。 (2认同)

Mik*_*ard 11

要使用特定类型的值,比如Int64,您可以显式地转换set-variable中使用的值.

例如:

set-variable -name test -value ([int64]100) -option Constant
Run Code Online (Sandbox Code Playgroud)

去检查,

$test | gm
Run Code Online (Sandbox Code Playgroud)

你会发现它是一个Int64(而不是Int32,这对于值100来说是正常的).


Pao*_*sco 9

-option ConstantSet-Variablecmdlet 一起使用:

Set-Variable myvar -option Constant -value 100
Run Code Online (Sandbox Code Playgroud)

现在$myvar具有100的常量值并且无法修改.

  • 哇,那太笨重了。你必须使用 Set-Variable 来做到这一点,对吧? (3认同)

zet*_*t42 7

我真的很喜欢rob 的答案提供的语法糖:

const myConst = 42
Run Code Online (Sandbox Code Playgroud)

不幸的是,当您Set-Constantmodule 中定义函数时,他的解决方案无法按预期工作。当从模块外部调用时,它将在Set-Constant定义的模块范围内创建一个常量,而不是调用者的范围。这使得常量对调用者不可见。

以下修改后的函数修复了这个问题。该解决方案是基于这个答案的问题“有没有什么办法了PowerShell的模块来获得在其调用者的范围是什么?” .

function Set-Constant {
    <#
    .SYNOPSIS
        Creates constants.
    .DESCRIPTION
        This function can help you to create constants so easy as it possible.
        It works as keyword 'const' as such as in C#.
    .EXAMPLE
        PS C:\> Set-Constant a = 10
        PS C:\> $a += 13

        There is a integer constant declaration, so the second line return
        error.
    .EXAMPLE
        PS C:\> const str = "this is a constant string"

        You also can use word 'const' for constant declaration. There is a
        string constant named '$str' in this example.
    .LINK
        Set-Variable
        About_Functions_Advanced_Parameters
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, Position=0)] [string] $Name,
        [Parameter(Mandatory=$true, Position=1)] [char] [ValidateSet("=")] $Link,
        [Parameter(Mandatory=$true, Position=2)] [object] $Value
    )

    $var = New-Object System.Management.Automation.PSVariable -ArgumentList @(
        $Name, $Value, [System.Management.Automation.ScopedItemOptions]::Constant
    )
    
    $PSCmdlet.SessionState.PSVariable.Set( $var )
}

Set-Alias const Set-Constant
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 该函数在从定义它的模块外部调用时才有效。这是预期的用例,但我想添加一个检查,它是否是从同一个模块调用的(在这种情况下Set-Variable -scope 1应该可以工作),当我发现如何这样做时。
  • 我已经改名为参数-Mean-Value,与一致性Set-Variable
  • 该函数可以扩展为可选地设置Private,ReadOnlyAllScope标志。只需将所需的值添加到PSVariable构造函数的第三个参数中,该参数在上面的脚本中通过New-Object.