PowerShell은 상수를 지원합니까?
PowerShell에서 정수 상수를 선언하고 싶습니다.
그렇게하는 좋은 방법이 있습니까?
사용하다
Set-Variable test -option Constant -value 100
또는
Set-Variable test -option ReadOnly -value 100
"Constant"와 "ReadOnly"의 차이점은 읽기 전용 변수는 다음을 통해 제거 (다시 생성) 할 수 있다는 것입니다.
Remove-Variable test -Force
반면 상수 변수는 제거 할 수 없습니다 (-Force를 사용하더라도).
자세한 내용은 이 TechNet 문서 를 참조하십시오.
다음은 다음과 같이 상수를 정의하는 솔루션입니다.
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
특정 유형의 값 (예 : Int64)을 사용하려면 set-variable에 사용 된 값을 명시 적으로 캐스팅 할 수 있습니다.
예를 들면 :
set-variable -name test -value ([int64]100) -option Constant
확인하다,
$test | gm
그리고 그것은 Int64 (값 100에 대해 정상인 Int32가 아니라)임을 알 수 있습니다.
cmdlet -option Constant과 함께 사용 Set-Variable:
Set-Variable myvar -option Constant -value 100
Now $myvar has a constant value of 100 and cannot be modified.
I really like the syntactic sugar that rob's answer provides:
const myConst = 42
Unfortunately his solution doesn't work as expected when you define the Set-Constant function in a module. When called from outside the module, it will create a constant in the module scope, where Set-Constant is defined, instead of the caller's scope. This makes the constant invisible to the caller.
The following modified function fixes this problem. The solution is based on this answer to the question "Is there any way for a powershell module to get at its caller's scope?".
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()] $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
Notes:
- The function only works, when called from outside the module, where it is defined. This is the intended use case, but I would like to add a check, whether it's called from the same module (in which case
Set-Variable -scope 1should work), when I have found out how to do so. - I've renamed the parameter
-Meanto-Value, for consistency withSet-Variable. - The function could be extended to optionally set the
Private,ReadOnlyandAllScopeflags. Simply add the desired values to the 3rd argument of thePSVariableconstructor, which is called in the above script throughNew-Object.
PowerShell v5.0 should allow
[static] [int] $variable = 42
[static] [DateTime] $thisday
and the like.
참고URL : https://stackoverflow.com/questions/2608215/does-powershell-support-constants
'Programing' 카테고리의 다른 글
| Real World Haskell의 어느 부분이 현재 쓸모 없거나 나쁜 습관으로 간주됩니까? (0) | 2020.08.14 |
|---|---|
| SQL ANSI-92 표준이 ANSI-89보다 더 잘 채택되지 않는 이유는 무엇입니까? (0) | 2020.08.14 |
| 왜 RGB가 아닌 RGB입니까? (0) | 2020.08.14 |
| 오류 (0) | 2020.08.14 |
| Rest API 서버용 Scala 프레임 워크? (0) | 2020.08.14 |