Cmdlet intrepretation of command line args in a function

Discussion in 'Scripting' started by Keith Hill, Nov 3, 2005.

  1. Keith Hill

    Keith Hill Guest

    Given I have a function def like this in my profile:

    remove-item alias:dir
    function dir {
    get-childitem $args | sort-object MshIsContainer -descending
    }

    I run into trouble if I try to do this:

    dir . -Include "*.cs" -Recurse

    The function invocation of get-childitem wants to treat each element of args
    as a path instead of generic input args. Any ideas on how to get around
    this?
     
    Keith Hill, Nov 3, 2005
    #1
    1. Advertisements

  2. Yeah - this is broken - $args get's passed as a single element to the inner
    command. Unfortunately there really isn't a good workaround. We're
    discussing way's of fixing this...
     
    Bruce Payette [MSFT], Nov 4, 2005
    #2
    1. Advertisements

  3. Keith Hill

    Keith Hill Guest

    Thanks for the heads up. This would be a really good bug to fix otherwise
    this workaround for alias's lack of argument pass through winds up pretty
    limited.
     
    Keith Hill, Nov 4, 2005
    #3
  4. Keith Hill

    Keith Hill Guest

    If you require new syntax in order to fix this might I suggest using $* to
    represent the arguments to be passed to some command as if they were typed
    in at the console. Both KSH and DOSKEY use this syntax for the same thing.
     
    Keith Hill, Nov 4, 2005
    #4
  5. One way to work around this for now is to have your function contain the
    same arguments as get-childitem.

    function dir ([string[]]$path, [string[]]$include, [string[]]$exclude,
    [string]$filter, [bool]$recurse)
    {
    get-childitem -path:$path -include:$include -exclude:$exclude -filter:$filter
    -recurse:$recurse | sort-object MshIsContainer -descending
    }
     
    Jeff Jones [MSFT], Nov 4, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.