locked
Adding an Undefined number of objects to an array RRS feed

  • Question

  • So I am trying to make a script that will allow me to pipe several user ids to it and spit out some information concerning each.


    function Get-UserID
    {                                                
        [CmdletBinding()]
        Param
        (
            [Parameter(Mandatory=$true,
                       ValueFromPipeline=$true,
                       Position=0,
                       HelpMessage = "Enter one or more User IDs in the format ABC1234.")]
            [ValidatePattern('^[A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9]$')]
            $UserID = $null
        )
    
        Begin
            {
                $UserInfo = @()
                $T = 0
    
            }#End BEGIN
        Process
            {
    
                foreach ($User in $UserID)
                    {
                        Write-Verbose "Processing $UserID"
                        $UserInfo[$T] = Get-ADUser -Filter "samaccountname -eq '$User'" | 
                            Select-Object @{name = "UserID"; expression = {$_.samaccountname}}, Name 
                        $T ++
                    }#End FOREACH
            }#End PROCESS
        End
            {
                $UserInfo #Displays Results
            }#EndEND
    }
    

    I keep getting the error:

    Index was outside the bounds of the array.
    At line:53 char:21
    + ...             $UserInfo[$T] = Get-ADUser -Filter "samaccountname -eq '$ ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : OperationStopped: (:) [], IndexOutOfRangeException
        + FullyQualifiedErrorId : System.IndexOutOfRangeException

    I am sure it is because the array size is not defines, I tested by adding the value (1..100) to the array and it worked out well aside form having all the extra numbers displayed. What is the best method for defining the array so this will work?

    Thursday, December 7, 2017 12:30 AM

All replies

  • This would work better:

    function Get-UserID {
        Param(
            [Parameter(
                Mandatory = $true,
                ValueFromPipeline = $true,
                HelpMessage = 'Enter one or more User IDs in the format ABC1234'
            )]
            [ValidatePattern('^[A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9]$')]
            [string[]]$UserID
        )
        Process{
            $UserID |
                ForEach-Object{
                        Write-Verbose "Processing $_"
                        Get-ADUser -Filter "samaccountname -eq '_'" | Select-Object @{ name = "UserID"; expression = { $_.samaccountname } }, Name
                }
        }
    }


    \_(ツ)_/



    Thursday, December 7, 2017 1:05 AM