0

I am trying to call Get-ChildItem function from custom function. The problem is the arguments to the function can be dynamic.

function Test {
    Get-ChildItem $Args
}

When I try

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

How to wrap around function and pass the arguments as it's?

3
  • 3
    Get-ChildItem @Args Commented Aug 19, 2016 at 11:25
  • @PetSerAl Waaay better than IEX hack, I've forgot that one can splat arrays. Should be an answer. Commented Aug 19, 2016 at 17:26
  • @PetSerAl, can you post your answer? I believe this is better than IEX. and IEX doesn't support space separated arguments. This supports everything Commented Aug 23, 2016 at 2:24

2 Answers 2

3

$args is an array of arguments, and passing it to the Get-ChildItem wouldn't work, as you've noticed. The PowerShell-way for this would be the Proxy Command.

For a quick-and-dirty hack, you can use Invoke-Expression:

function Test {
    Invoke-Expression "Get-ChildItem $Args"
}
Sign up to request clarification or add additional context in comments.

Comments

1

Invoke-Expression will be difficult to work with because what's been passed as strings will need quoting all over again when expressed in a string. ProxyCommand is the better way as beatcracker has suggested.

There are a few alternatives for fun and interest. You might splat PSBoundParameters, but you will need to declare the parameters you expect to pass.

This is an incomplete example in that it will easily get upset if there are duplicate parameters (including common parameters if you set CmdletBinding on the function Test).

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.