programing

PowerShell의 스위치 매개 변수와 같은 열거형

itmemos 2023. 8. 20. 10:19
반응형

PowerShell의 스위치 매개 변수와 같은 열거형

이러한 방식으로 PowerShell 스크립트에서 스위치 매개 변수를 사용하고 있습니다.

param(
    [switch] $Word,
    [switch] $Excel,
    [switch] $powerpoint,
    [switch] $v2007,
    [switch] $v2010,
    [switch] $x86,
    [switch] $x64,
)

나는 그것을 좀 더 열거적인 스타일로 만들기 위해 어떤 깔끔한 방법을 찾으려고 노력하고 있습니다.누구나 짐작하듯이, 저는 사용자가 워드, 엑셀, 파워포인트 중에서 선택하기를 원합니다.그리고 x2007과 v2010 사이에.

입력 매개변수 열거형을 가져오는 깔끔한 방법이 있습니까?

PowerShell은 처음입니다.그래서 만약 이것이 제가 명백한 것을 모르는 것처럼 들린다면, 제가 그것에 대해 읽을 수 있는 링크를 가르쳐 주세요.

사용할 수 있습니다.ValidateSet대신 매개 변수 속성을 사용합니다.

보낸 사람: 정보_함수_고급_매개변수

ValidateSet 특성은 매개 변수 또는 변수에 대한 유효한 값 집합을 지정합니다.매개 변수 또는 변수 값이 집합의 값과 일치하지 않으면 Windows PowerShell에서 오류를 생성합니다.

함수 예제:

function test-value
{
    param(
        [Parameter(Position=0)]
        [ValidateSet('word','excel','powerpoint')]
        [System.String]$Application,

        [Parameter(Position=1)]
        [ValidateSet('v2007','v2010')]
        [System.String]$Version
    )


    write-host "Application: $Application"
    write-host "Version: $Version"
}   


PS > test-value -application foo

출력:

test-value : Cannot validate argument on parameter 'Application'. The argument "foo" does not belong to the set "word,excel,powerpoint" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.

사용할 수 있습니다.ValidateSet속성:

function My-Func
{
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('Word', 'Excel', 'PowerPoint', 'v2007', 'v2010', 'x86', 'x64')]
        [String]$MyParam
    )

    Write-Host "Performing action for $MyParam"
}

My-Func -MyParam 'Word'
My-Func -MyParam 'v2007'
My-Func -MyParam 'SomeVal'

출력:

Performing action for Word
Performing action for v2007
My-Func : Cannot validate argument on parameter 'MyParam'. The argument "SomeVal" does not belong to the set "Word,Excel,PowerPoint,v2007,v2010,x86,x64" specified by the ValidateSet attribute. Supply an argument that is in the
 set and then try the command again.
At C:\Users\George\Documents\PowerShell V2\ValidateSetTest.ps1:15 char:17
+ My-Func -MyParam <<<<  'SomeVal'
    + CategoryInfo          : InvalidData: (:) [My-Func], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,My-Func

PowerShell 팀의 이 블로그 게시물은 PowerShell 1.0에서 이를 수행하는 방법을 정의합니다.PowerShell 2.0에서는 다음과 같이 Add-Type을 사용할 수 있습니다.

C:\PS> Add-Type -TypeDefinition @'
>> public enum MyEnum {
>> A,
>> B,
>> C,
>> D
>> }
>> '@
>>

업데이트: 열거형을 사용하는 방법은 다음과 같습니다.

C:\PS> function foo([MyEnum]$enum) { $enum }
C:\PS> foo ([MyEnum]::A)
A

인수를 유형으로 구문 분석하려면 인수 주위의 괄호가 필요합니다.인수는 문자열과 거의 동일하게 처리되므로 이 작업이 필요합니다.이것을 알면 간단한 문자열 형태로 열거형을 전달할 수 있으며 파워셸은 다음을 알아낼 것입니다.

C:\PS> foo A
A
C:\PS> $arg = "B"
C:\PS> foo $arg
B
C:\PS> foo F
error*

오류 - F는 열거된 값 중 하나가 아닙니다. 유효한 값은 A,B,C,D *를 포함합니다.

PowerShell 5부터는 실제로 사용/생성할 수 있습니다.Enum토속적으로

enum OS {
    Windows
    Linux
    iOS
}

그러면 유형으로도 볼 수 있습니다.

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     OS                                       System.Enum

아마도 4개의 sysops에 의한 유용한 링크일 것.

함수에 사용하려면 별도로 생성해야 합니다..psm1파일을 작성하고 필요한 모든 열거형을 추가합니다. 유사한 질문을 참조하는 내 의견을 참조하십시오. 또는 이 열거형을 맨 위에 설정할 수 있습니다..psm1파일을 저장하고 동일한 파일에서 사용합니다.

예를 들어, 파일을 만들었습니다.test.psm1다음 코드를 추가했습니다.

enum OS {
    Windows
    Linux
    iOS
}

function Get-OS {
    param (
        [Parameter(Mandatory)]
        [OS]$os
    )

    Write-Host -Object "The operating system is $os."
    
}

파일을 가져옵니다.Import-Module .\test.psm1실행:

PS > Get-OS -os Linux
The operating system is Linux.

언급URL : https://stackoverflow.com/questions/3736188/enum-like-switch-parameter-in-powershell

반응형