首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PowerShell支持常量吗?

PowerShell支持常量吗?
EN

Stack Overflow用户
提问于 2010-04-09 22:22:01
回答 5查看 72K关注 0票数 128

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

有什么好方法可以做到这一点吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-04-09 23:11:18

使用

代码语言:javascript
复制
Set-Variable test -Option Constant -Value 100

代码语言:javascript
复制
Set-Variable test -Option ReadOnly -Value 100

Constant“和"ReadOnly”之间的区别在于,只读变量可以通过

代码语言:javascript
复制
Remove-Variable test -Force

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

有关更多详细信息,请参阅this TechNet article

票数 134
EN

Stack Overflow用户

发布于 2013-07-25 00:28:41

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

代码语言:javascript
复制
const myConst = 42

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

代码语言:javascript
复制
    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
票数 16
EN

Stack Overflow用户

发布于 2013-07-25 03:22:31

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

例如:

代码语言:javascript
复制
set-variable -name test -value ([int64]100) -option Constant

为了检查,

代码语言:javascript
复制
$test | gm

您将看到它是一个Int64 (而不是Int32,这对于值100来说是正常的)。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2608215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档