2014-11-19 1 views
0

특정 명명 된 매개 변수를 따르는 값 모자를 수집하는 함수를 작성하고 있습니다. 코드는-weatch와 정규 표현식에 관한 powershell의 형변환 문제

[email protected]("ddddd","-anotherswitch2","djfjdsfa","-recurse",1,2,3,"-anotherswitch","-recurse",5,6, "-anotherswitch","kslsdfgvl") 

$searchswitch="-recurse" 
[email protected]() 
$matches=0 
$counter=0    

while (($Counter -lt $commandline.length-1) -AND ($matches -lt 1))      
{ 

    if ($commandline[$counter] -eq $searchswitch) 
    { 
     $matches++ 
     $counter++ 

     # while argument does not start with "-" and we haven't reached the end of the array 

     While(-NOT ($commandline[$counter] -match "^-") -AND ($counter -lt $commandline.length)) 

     { 
      $Paths+= $($commandline[$counter]) 
      $counter++ 

     }     
    } 
    else 
    { 
     $counter++ 
    } 
} 

$Paths 

코드는 예상대로 거의 작동 (데모 목적으로이 등 매개 변수를 구문 분석하지 않고만을 발췌 한 것입니다)하지만, 다음과 같은 오류 메시지가 발생 다음과 같다.

Der Wert "System.Collections.Hashtable" vom Typ "System.Collections.Hashtable" kann nicht in den Typ "System.Int32" konvertiert werden. 
Bei D:\Unbenannt5.ps1:18 Zeichen:67 
+       While(-NOT ($commandline[$counter] -match <<<< "^-") -AND ($counter -lt $commandline.length)) 
    + CategoryInfo   : MetadataError: (:) [], ArgumentTransformationMetadataException 
    + FullyQualifiedErrorId : RuntimeException 

1 
2 
3 

오류 메시지가 "선택 System.Int32" 유형으로 변환 할 수없는 유형의 값 "System.Collections.Hashtable" "System.Collections.Hashtable"의 독일어 버전입니다.

나는 이것을 명령 행 배열의 8 번째 요소 (-anotherswitch)로 좁혔다. 아무도 도와 줄 수 있니? 미리 감사드립니다.

+0

네, 맞아요. 필자는 §args 기반 접근 방식에이 기능을 부여하여 함수에 구문 분석을 수행하는 기본 Powershell 매개 변수를 얻으려고했습니다. 'param()'으로 네이티브 powershell 접근법을 사용하면 전체 함수는 쓸모 없게됩니다 :-) 그러나 나는 에러의 원인을 아는 데 관심이 있습니다. 매개 변수 이름에 하이픈 - 빼기 기호를 사용해야 할 수도 있습니다. – user3210625

답변

2

정확하게 해석하면이 코드는 임의의 수의 추가 매개 변수를 사용할 수 있도록 만들어졌습니다. 그렇다면, 내가 당신이 쉽게 할 수 있도록하십시오

function My-Function { 
[CmdletBinding()] 
param(
    [Parameter()] 
    [Switch] 
    $Recurse , # I'm guessing the arbitrary number of parameters comes after this 

    [Parameter(
     ValueFromRemainingArguments=$true 
    )] 
    $Remaining 
) 
    $Remaining # This is an array of all the extra arguments 
} 

나는 이것이 당신이 가지고 정확한 질문에 대답하지 않을 수 있습니다, 대신 모든 코드에 대한 필요성을 회피 할 수있는 방법이 될 수 있습니다 알고 있습니다.

내가하려는 것을 정확하게 포착하지 못했다면 전체 기능을 설명하거나 보여주십시오.

4

-match 연산자는 $Matches이라는 변수에서 모든 일치 항목을 반환하고 같은 이름의 변수를 덮어 씁니다.

-match 설명 :

PS C:\> "foo" -match "f[o]o" 
True 
PS C:\> $Matches 

Name       Value 
----       ----- 
0        foo 

, 그래서 같이이 documented는 기능입니다 정규 표현식을 사용하여 문자열을 일치시킵니다. 입력이 스칼라 인 경우 $ 자동 변수를 채 웁니다.

해결책 : 변수에 다른 이름을 사용하십시오.