Advanced function array input

This topic contains 6 replies, has 2 voices, and was last updated by  Don Jones 10 months, 2 weeks ago.

  • Author
  • #78838


    I am creating an advanced function and having a problem accepting array. So to explain:

    I can run this ok:
    Get-MyCmdlet 'c:\test.txt'

    When I run:

    Get-MyCmdlet 'c:\test.txt', 'c:\test2.txt'

    It see the 2nd in the array as a second parameter and get the error:

    Cant find an overload for "xxx" and the argument count: "2"

    How do I get it to recognise anything after the comma as being part of the first parameter.

    For instance Get-Process can be run as:

    Get-Process 'winword', 'explorer'

  • #78841

    Don Jones

    It would help to see your parameter declaration block.

  • #78848


    # Path to an MSI file

    I've just realised that it is sending it through when I added ValueFromRemainingArguments=$true. However It is now passing it through as a string[] rather than dealing with it in the begin,process,end block as individual strings like passing on the pipeline does

  • #78851

    Don Jones

    So, it's a bit hard to tell with unformatted code, but:

    'c:\test.txt', 'c:\test2.txt'

    Aren't necessarily the same; PowerShell uses a space to detect where one value stops and the next parameter value begins. Because you're using positional parameters, you leave a lot up to the shell's discretion. If you really want to test this, use:

    Get-MyCmdlet -Path @('c:\test.txt','c:\test2.txt')

    That'll tell you if the parameter is working as intended, since the @() array operator explicitly forces an array. If you really want to dig into the troubleshooting, use Trace-Command to view a parameterbinding dump of your command bring run with two array items – that'll show you exactly what PowerShell is trying to do under the hood.

  • #78859


    So how does both of these work in terms of your definition then?

    get-process 'explorer', 'svchost'
    get-process 'explorer','svchost'
  • #78862


    Ok... resolved 🙂

    The problem was further down the stack.

    The comma seems to denote that something else is coming for the parameter so it doesn't matter if you have a space after the comma or not, the next parameter follows a space without a preceding comma

    The problem is that I was expecting the begin,process,end block to handle the variables in the array individually like it does if you were passing something through the pipeline. It doesn't it passes a whole array through, so you have to process the array yourself.

  • #78863

    Don Jones

    Ah. Correct. I cover that in my Toolmakong book :).

You must be logged in to reply to this topic.