2011-03-25 3 views
4

Powershell 스크립트 파일에서 params를 파싱하는 쉬운 방법이 있습니까?Powershell 스크립트 매개 변수 분석

param(
    [string]$name, 
    [string]$template 
) 

파일 읽기를 시작했고 더 나은 방법이 있는지 궁금해 할 수 있습니다.

class PowerShellParameter { 
    public string Name; 
    public string Type; 
    public string Default; 
} 

string[] lines = File.ReadAllLines(path); 
bool inparamblock = false; 
for (int i = 0; i < lines.Length; i++) { 
    if (lines[i].Contains("param")) { 
     inparamblock = true; 
    } else if (inparamblock) { 
     new PowerShellParameter(...) 
     if (lines[i].Contains(")")) { 
      break; 
     } 
    } 
} 

답변

4

최소한 두 가지 가능성이 있습니다. (더 나은 이럴) 먼저 하나를 사용 Get-Command : 모든 회원들에 대한

# my test file 
@' 
param(
    $p1, 
    $p2 
) 

write-host $p1 $p2 
'@ | Set-content -path $env:temp\sotest.ps1 
(Get-Command $env:temp\sotest.ps1).parameters.keys 

Get-Command $env:temp\sotest.ps1 | gm 
#or 
Get-Command $env:temp\sotest.ps1 | fl * 

다른 (더 열심히 방법) 봐 난

[regex]::Matches((Get-Help $env:temp\sotest.ps1), '(?<=\[\[-)[\w]+') | select -exp Value 
1

정규 표현식을 사용하는 것입니다 당신이 뭘하고 있는지 잘 모르겠다. 스크립트를 문서화하고 있는가? 이 경우 Get-Help about_Comment_Based_Help을보십시오. 이를 수행하는 방법을 알려주고 그 후에 스크립트/모듈에 Get-Help을 사용할 수 있습니다.

보다 엄격한 매개 변수 처리를 수행하려는 경우 매개 변수 구조를 개선하는 방법에 대해서는 about_functions_advanced_parametersabout_functions_cmdletbindings을 살펴보십시오. 예를 들어,

[Parameter(Position=0,Mandatory=$true,HelpMessage='Enter architecture("OSX","WinXP","Win7","Linux")')] [ValidateSet("OSX","WinXP","Win7","Linux")] [string]$architecture

은 지정된 세트 만 값을 허용 명령의 위치 0에서 읽을 필수 그 매개 변수를 확인하고 입력하는 경우를 묻는 간단한 도움말 메시지를 줄 것이다 그 매개 변수는 주어지지 않았다.

3

@stej가 제안한 Get-Command의 솔루션이 마음에 든다. 아쉽게도 스크립트 매개 변수에 명시 적 유형이 지정되어 있고 해당 유형의 어셈블리가 아직 세션에로드되지 않은 경우 작동하지 않습니다. 이것이 내가이 스크립트를 사용하는 이유입니다. Get names of script parameters

+0

+1 System.Management.Automation.PSParser.Tokenize를 살펴 봐야 할 것입니다. – djeeg

관련 문제