2016-08-19 4 views
0

사용자 정의 함수에서 Get-ChildItem 함수를 호출하려고합니다. 문제는 함수에 대한 인수가 동적 일 수 있다는 것입니다.Powershell에서 문자열로 인수를 사용하여 함수 호출

function Test { 
    Get-ChildItem $Args 
} 

내가

Test .\ //this works as Path is taken as default argument value 
Test .\ -Force //this doesn't work as expected as it still tries to consider entire thing as Path 
Test -Path .\ -Force //same error 

방법 wrap around functionpass the arguments as it's를 시도?

+3

은'은 Get-ChildItem을 @ Args' – PetSerAl

+0

@PetSerAl Waaay IEX 해킹보다 더, 나는 하나의 배열을 플랫 수 있다는 것을 잊었습니다. 대답이어야합니다. – beatcracker

+0

@PetSerAl, 답변을 게시 할 수 있습니까? 나는 이것이 IEX보다 낫다고 믿는다. IEX는'space separated arguments'를 지원하지 않습니다. 이것은 모든 것을 지원한다. – Reddy

답변

3

$args은 인수 배열이며 Get-ChildItem에 전달하는 것으로 나타났습니다. 이를위한 PowerShell 방식은 Proxy Command입니다.

function Test { 
    Invoke-Expression "Get-ChildItem $Args" 
} 
1

호출 표현이 표현 될 때 문자열이 모든 것을 다시 인용해야하므로 무엇을하는 것은 전달되어 있기 때문에 작업하기 어려울 것이다

더러운 빠른 및 해킹에 대한

, 당신은 Invoke-Expression 사용할 수 있습니다 끈. beatcracker가 제안한대로 ProxyCommand가 더 좋은 방법입니다.

재미와 흥미를위한 몇 가지 대안이 있습니다. PSBoundParameters를 표시 할 수 있지만 전달할 매개 변수를 선언해야합니다.

중복 된 매개 변수 (Test 함수에서 CmdletBinding을 설정하면 공통 매개 변수 포함)가있는 경우이 매개 변수가 쉽게 작동하지 않는다는 점에서 불완전한 예입니다.

function Test { 
    dynamicparam { 
     $dynamicParams = New-Object Management.Automation.RuntimeDefinedParameterDictionary 

     foreach ($parameter in (Get-Command Microsoft.PowerShell.Management\Get-ChildItem).Parameters.Values) { 
      $runtimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter(
       $parameter.Name, 
       $parameter.ParameterType, 
       $parameter.Attribtes 
      ) 
      $dynamicParams.Add($parameter.Name, $runtimeParameter) 
     } 

     return $dynamicParams 
    } 

    end { 
     Get-ChildItem @psboundparameters 
    } 
} 
관련 문제