Home > OS >  How to only allow array parameter of a certain length
How to only allow array parameter of a certain length

Time:11-19

I'm currently studying advanced functions for my PowerShell module and was tasked with a problem I don't think was properly covered in the class.

Here's said problem.

Create an advanced function using Begin, Process, and End, that takes two(2) arguments. The first argument being an array of at least ten(10) integers and the second argument being a single integer. Search the array argument for every occurrence of the single integer argument then return the sum of all elements in the array excluding every occurrence of the single integer argument.

I am unable to figure out the 'at least ten(10) integers' part.

Here's the script that I wrote.

function get-multisum
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [ValidateLength(10)]
        [array]$array,
        [Parameter(Mandatory=$true)]
        [int32]$num
    )
    Begin {
        $total = 0
    }
    Process {
        foreach($i in $array)
        {
            if($i -ne $num)
            {
                $total = $total   $i
            }
            else {
                continue
            }
        }
    }
    End {
        return $total
    }
}

While I understand this could be written like...

function problem($array, $num)
{
    foreach($i in $array)
    {
        if($i -ne $num)
        {
            $total = $total   $i
        }
    }   
    return $total
}

The question specifically prompted for an advanced function. My script works as intended OTHER THAN the validation of the array having at least 10 elements. I experimented with [ValidateLength(10)] but that didn't work. I don't want to run the check after the code begins with some if statement or what have you. I'm curious if there's away to only allow valid parameters in the first place. Thanks in advance!

CodePudding user response:

The solution they're probably after may differ from this but, you can validate the count of how many items are passed to your parameter using the [ValidateCount()] attribute:

Function Test {
[CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [ValidateCount(10,[int]::MaxValue)]
        [int[]]$IntArray,

        [Parameter(Mandatory)]
        [int]$SingleInt
    )
    if (($remainding = $IntArray.Where{$_ -ne $SingleInt}).Count -ne $IntArray.Count)
    { 
        ($remainding | Measure-Object -Sum).Sum 
    }
}

Here, 10 is the minimum amount of values passed to that parameter and [int]::MaxValue being max it can be passed.

So the following should fail:

test -IntArray (1..9) # fails

While this passes:

test -IntArray (1..10)

It's also good to note that type-constraining it to [int[]] rather than [array] may be closer to what they're asking of. [array] would be able to accept other values other than integers as well.

  • Related