我想在PowerShell中声明一些整数常量。
有什么好方法可以做到这一点吗?
发布于 2010-04-09 23:11:18
使用
Set-Variable test -Option Constant -Value 100
或
Set-Variable test -Option ReadOnly -Value 100
Constant“和"ReadOnly”之间的区别在于,只读变量可以通过
Remove-Variable test -Force
而常量变量不能被删除(即使使用-Force)。
有关更多详细信息,请参阅this TechNet article。
发布于 2013-07-25 00:28:41
下面是定义这样一个常量的解决方案:
const myConst = 42
取自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
发布于 2013-07-25 03:22:31
要使用特定类型的值,例如Int64,您可以显式转换set-variable中使用的值。
例如:
set-variable -name test -value ([int64]100) -option Constant
为了检查,
$test | gm
您将看到它是一个Int64 (而不是Int32,这对于值100来说是正常的)。
https://stackoverflow.com/questions/2608215
复制相似问题